Example #1
0
        /// <summary>
        /// 预下单请求
        /// </summary>
        /// <returns></returns>
        public static PrecreateResponseModel Prepay(PrecreateModel precreateModel)
        {
            AlipayTradePrecreateRequest payRequst = new AlipayTradePrecreateRequest();

            if (precreateModel.extend_params == null)
            {
                precreateModel.extend_params = new ExtendParams();
            }
            precreateModel.extend_params.sys_service_provider_id = Config.providerid;
            payRequst.BizContent = JsonConvert.SerializeObject(precreateModel);
            LogUtil.WriteAlipayLog("预下单请求", "请求参数", payRequst.BizContent);
            //需要异步通知的时候,需要是指接收异步通知的地址。
            payRequst.SetNotifyUrl("http://10.5.21.14/notify_url.aspx");
            Dictionary <string, string>  paramsDict  = (Dictionary <string, string>)payRequst.GetParameters();
            AlipayTradePrecreateResponse payResponse = _client.Execute(payRequst);

            LogUtil.WriteAlipayLog("预下单响应", "响应原始参数", payResponse.Body);
            return(new PrecreateResponseModel
            {
                code = payResponse.Code,
                msg = payResponse.Msg,
                subcode = payResponse.SubCode,
                submsg = payResponse.SubMsg,
                out_trade_no = payResponse.OutTradeNo,
                qr_code = payResponse.QrCode
            });
        }
Example #2
0
        /// <summary>
        /// 获取扫码支付的二维码图片链接
        /// </summary>
        /// <param name="orderNo">商户订单号,64个字符以内、只能包含字母、数字、下划线;需保证在商户端不重复</param>
        /// <param name="amount">订单总金额,单位为元,精确到小数点后两位,取值范围[0.01,100000000] 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】</param>
        /// <param name="subject">订单标题</param>
        /// <param name="body">商品描述信息</param>
        /// <param name="storeId">商户门店编号</param>
        /// <returns></returns>
        public string GetQrCodeUrl(string orderNo, decimal amount, string subject, string body, string storeId)
        {
            string link = string.Empty;

            //组装业务参数
            var model = new AlipayTradePrecreateModel()
            {
                Body        = body,
                Subject     = subject,
                TotalAmount = amount.ToString(),
                OutTradeNo  = orderNo,
                StoreId     = storeId //商户门店编号
            };

            var request = new AlipayTradePrecreateRequest();

            request.SetBizModel(model);
            request.SetNotifyUrl(NotifyUrl);

            AlipayTradePrecreateResponse response = aopClient.Execute(request);

            if (response != null && response.Code == "10000")
            {
                link = response.QrCode;
            }
            return(link);
        }
Example #3
0
 private T Execute <T>(IAopRequest <T> request) where T : AopResponse
 {
     if (string.IsNullOrEmpty(AuthToken))
     {
         return(client.Execute(request));
     }
     return(client.Execute(request, null, AuthToken));
 }
Example #4
0
        public AlipayTradePayResponse Pay(string content)
        {
            AlipayTradePayRequest payRequst = new AlipayTradePayRequest();

            payRequst.BizContent = content;
            //Dictionary<string, string> paramsDict = (Dictionary<string, string>)payRequst.GetParameters();
            AlipayTradePayResponse payResponse = m_Client.Execute(payRequst);

            return(payResponse);
        }
Example #5
0
        /// <summary>
        /// 请求支付宝创建订单接口
        /// </summary>
        /// <param name="biz_content"></param>
        /// <returns></returns>
        private AlipayTradePrecreateResponse Prepay(string biz_content)
        {
            AlipayTradePrecreateRequest payRequst = new AlipayTradePrecreateRequest();

            payRequst.BizContent = biz_content;
            //需要异步通知的时候,需要是指接收异步通知的地址。
            payRequst.SetNotifyUrl("http://alipayapi.zhilvtx.com/API/ALIPAY/Notify");
            Dictionary <string, string>  paramsDict  = (Dictionary <string, string>)payRequst.GetParameters();
            AlipayTradePrecreateResponse payResponse = client.Execute(payRequst);

            return(payResponse);
        }
Example #6
0
        private AlipayTradePayResponse Pay(string biz_content)
        {
            AlipayTradePayRequest payRequst = new AlipayTradePayRequest();

            payRequst.BizContent = biz_content;

            Dictionary <string, string> paramsDict = (Dictionary <string, string>)payRequst.GetParameters();
            //new DefaultAopClient(Config.serverUrl, Config.appId, Config.merchant_private_key);

            AlipayTradePayResponse payResponse = client.Execute(payRequst);

            return(payResponse);
        }
        public void TestMethod1()
        {
            IAopClient client = GetAlipayClient();
            AlipayMobilePublicMultiMediaDownloadRequest req = new AlipayMobilePublicMultiMediaDownloadRequest();

            string path = "c:/1.jpg";

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            FileStream fs = new FileStream(path, FileMode.CreateNew);

            req.stream = fs;

            string mediaId = "L21pZnMvVDFQV3hYWGJKWFhYYUNucHJYP3Q9YW13ZiZ4c2lnPTU0MzRhYjg1ZTZjNWJmZTMxZGJiNjIzNDdjMzFkNzkw575";

            req.BizContent = "{\"mediaId\":\"" + mediaId + "\"}";

            AlipayMobilePublicMultiMediaDownloadResponse res = client.Execute(req);

            System.Console.WriteLine("-------------公众号菜单查询-------------");

            System.Console.WriteLine("Body:" + res.Body);
            System.Console.ReadLine();
        }
Example #8
0
        private AlipayTradePrecreateResponse Prepay(string biz_content)
        {
            AlipayTradePrecreateRequest payRequst = new AlipayTradePrecreateRequest();

            payRequst.BizContent = biz_content;

            //需要异步通知的时候,需要是指接收异步通知的地址。
            payRequst.SetNotifyUrl("http://10.5.21.14/notify_url.aspx");

            Dictionary <string, string> paramsDict = (Dictionary <string, string>)payRequst.GetParameters();
            //new DefaultAopClient(Config.serverUrl, Config.appId, Config.merchant_private_key);

            AlipayTradePrecreateResponse payResponse = client.Execute(payRequst);

            return(payResponse);
        }
Example #9
0
        public AlipayData Query(string id, OrderType outTradeNo)
        {
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            var requstData = "{\"" + (outTradeNo == OrderType.OutTradeNo ? "out_trade_no" : "trade_no") + "\":\"" + id + "\"}";

            //string.Format(, outTradeNo == OrderType.OutTradeNo ? "out_trade_no" : "trade_no",id);
            request.BizContent = requstData;
            var response   = _aopClient.Execute(request);
            var alipayData = new AlipayData();

            if (response.IsError)
            {
                LogHelper.Logger.Error("查询订单失败:" + response.Msg + "," + response.SubMsg);
                if (response.Code == "40004")
                {
                    alipayData.SetValue("trade_status", "NOPAY");
                    alipayData.SetValue(outTradeNo == OrderType.OutTradeNo ? "out_trade_no" : "trade_no", id);
                    return(alipayData);
                }

                throw new Exception("查询订单失败,原因" + response.Msg);
            }
            alipayData.SetValue("trade_status", response.TradeStatus);
            alipayData.SetValue("trade_no", response.TradeStatus);
            alipayData.SetValue("out_trade_no", response.OutTradeNo);
            alipayData.SetValue("buyer_logon_id", response.BuyerLogonId);
            alipayData.SetValue("total_amount", response.TotalAmount);
            alipayData.SetValue("receipt_amount", response.ReceiptAmount);
            alipayData.SetValue("buyer_pay_amount", response.BuyerPayAmount);
            return(alipayData);
        }
Example #10
0
        public Refund BuildRefundQuery(Refund refund)
        {
            IAopClient alipayClient = GetAopClient();
            AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
            AlipayTradeFastpayRefundQueryModel   model   = new AlipayTradeFastpayRefundQueryModel();

            model.OutTradeNo = refund.OrderNo;
            if (!string.IsNullOrEmpty(refund.TradeNo))
            {
                model.TradeNo = refund.TradeNo;
            }
            model.OutRequestNo = refund.OutRefundNo;
            request.SetBizModel(model);
            AlipayTradeFastpayRefundQueryResponse response = alipayClient.Execute(request);

            if (response.Code == "10000" && !string.IsNullOrEmpty(response.RefundAmount))
            {
                double refundAmount;
                if (double.TryParse(response.RefundAmount, out refundAmount))
                {
                    if (refundAmount > 0.0)
                    {
                        refund.TradeNo      = response.TradeNo;
                        refund.RefundAmount = refundAmount;
                        refund.RefundStatus = true;
                    }
                }
            }
            return(refund);
        }
Example #11
0
        /// <summary>
        /// 获取授权码
        /// 当使用app_auth_code换取app_auth_token时,biz_content的内容如下:
        ///{
        ///    "grant_type": "authorization_code",
        ///    "code": "bf67d8d5ed754af297f72cc482287X62"
        ///}
        /// 当要刷新app_auth_token时,需要使用refresh_token,biz_content的内容如下:
        ///{
        ///    "grant_type": "refresh_token",
        ///    "refresh_token": "201510BB0c409dd5758b4d939d4008a525463X62"
        ///}
        /// </summary>
        /// <returns></returns>
        public AlipayOpenAuthTokenAppResponse OpenAuthTokenApp(OpenAuthTokenAppDTO dto)
        {
            AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();

            request.BizContent = dto.BuildJson();
            AlipayOpenAuthTokenAppResponse response = client.Execute(request);

            return(response);
        }
Example #12
0
        private static void MenuGet()
        {
            IAopClient client = GetAlipayClient();
            AlipayMobilePublicMenuGetRequest  req = new AlipayMobilePublicMenuGetRequest();
            AlipayMobilePublicMenuGetResponse res = client.Execute(req);

            System.Console.Write("-------------公众号菜单查询-------------" + "\n\r");
            System.Console.Write("Body:" + res.Body + "\n\r");
        }
Example #13
0
        private AlipayTradeQueryResponse Query(string biz_content)
        {
            AlipayTradeQueryRequest payRequst = new AlipayTradeQueryRequest();

            payRequst.BizContent = biz_content;

            Dictionary <string, string> paramsDict  = (Dictionary <string, string>)payRequst.GetParameters();
            AlipayTradeQueryResponse    payResponse = client.Execute(payRequst);

            return(payResponse);
        }
Example #14
0
        public string query(AlipayTradeQueryModel para)
        {
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

            // 将业务model载入到request
            request.SetBizModel(para);

            AlipayTradeQueryResponse response = client.Execute(request);

            return(response.Body);
        }
Example #15
0
        private AlipayTradeCancelResponse Cancel(string biz_content)
        {
            AlipayTradeCancelRequest cancelRequest = new AlipayTradeCancelRequest();

            cancelRequest.BizContent = biz_content;
            AlipayTradeCancelResponse cancelResponse = client.Execute(cancelRequest);

            if (null != cancelResponse)
            {
                if (cancelResponse.Code == qrcode._2.ResultCode.FAIL && cancelResponse.RetryFlag == "Y")
                {
                    for (int i = 0; i < retryCount; ++i)
                    {
                        Thread.Sleep(3000);
                        cancelResponse = client.Execute(cancelRequest);

                        if (null != cancelResponse)
                        {
                            if (cancelResponse.Code == qrcode._2.ResultCode.FAIL)
                            {
                                //if (cancelResponse.Body.Contains("\"retry_flag\":\"N\""))
                                if (cancelResponse.RetryFlag == "N")
                                {
                                    break;
                                }
                            }
                            if ((cancelResponse.Code == qrcode._2.ResultCode.SUCCESS))
                            {
                                break;
                            }
                        }

                        if (i == retryCount - 1)
                        {
                            throw new Exception("撤销订单失败!");
                        }
                    }
                }
            }
            return(cancelResponse);
        }
Example #16
0
        public void Query()
        {
            IAopClient client = GetClient();
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

            request.BizContent = "{" +
                                 "    \"out_trade_no\":\"20150320010101001\"," +
                                 "    \"trade_no\":\"2014112611001073956707\"" +
                                 "  }";

            AlipayTradeQueryResponse response = client.Execute(request);
        }
Example #17
0
        /// <summary>
        /// 获取扫码支付的二维码图片链接(将链接用二维码工具生成二维码打印出来,顾客可以用支付宝钱包扫码支付)
        /// </summary>
        public string GetQrCodePayLink(decimal amount, string orderNo, string subject, string body, string storeId, string operatorId)
        {
            string link = string.Empty;

            //组装业务参数
            var model = new AlipayTradePrecreateModel()
            {
                Body        = body,
                Subject     = subject,
                TotalAmount = amount.ToString(),
                OutTradeNo  = orderNo,
                StoreId     = storeId, //商户门店编号
                OperatorId  = operatorId
            };

            var request = new AlipayTradePrecreateRequest();

            request.SetBizModel(model);

            //不推荐使用异步通知,避免单边账问题发生。推荐使用轮询撤销机制
            //对所有唤起收银台的交易(支付宝返回状态10003(等待用户支付))发起轮询,并且建议轮询总时间设为30秒,轮询平均间隔设为3秒。在让用户再次支付前,必须通过查询确认当前订单的状态。
            //request.SetNotifyUrl(NotifyUrl);

            AlipayTradePrecreateResponse response = aopClient.Execute(request);

            if (response != null && response.Code == "10000")
            {
                link = response.QrCode;
            }

            //记日志response.ToJson();

            return(link);
        }
Example #18
0
        public ActionResult QrcodeRSAPay(string bizContent)
        {
            var op = new OpResult();
            AlipayTradePrecreateRequest payRequst = new AlipayTradePrecreateRequest();

            payRequst.BizContent = bizContent;

            //需要异步通知的时候,需要是指接收异步通知的地址。
            payRequst.SetNotifyUrl(qrcode._1.Config.Notify_url);
            Dictionary <string, string>  paramsDict  = (Dictionary <string, string>)payRequst.GetParameters();
            AlipayTradePrecreateResponse payResponse = client.Execute(payRequst);

            //以下返回结果的处理供参考。
            //payResponse.QrCode即二维码对于的链接
            //将链接用二维码工具生成二维码打印出来,顾客可以用支付宝钱包扫码支付。
            string result = payResponse.Body;

            if (payResponse != null)
            {
                switch (payResponse.Code)
                {
                case qrcode._2.ResultCode.SUCCESS:
                    var createUrl = Url.Action("GenerateQrcode", new { codeUrl = payResponse.QrCode });
                    op.Message   = Request.Url.Scheme + "://" + Request.Url.Authority + Url.Action("CreateQRCode", new { url = createUrl, paySN = payResponse.OutTradeNo });
                    op.Successed = true;
                    break;

                case qrcode._2.ResultCode.FAIL:
                    StringBuilder sb2 = new StringBuilder();
                    sb2.Append("{\"out_trade_no\":\"" + payResponse.OutTradeNo + "\"}");
                    Cancel(sb2.ToString());
                    op.Message = "预下单失败";
                    break;
                }
            }
            return(new JsonNetResult(op));
        }
        public AlipayF2FMonitorResult mcloudMonitor(AlipayMonitorContentBuilder build)
        {
            AlipayF2FMonitorResult result = new AlipayF2FMonitorResult();

            try
            {
                MonitorHeartbeatSynRequest monitorRequest = new MonitorHeartbeatSynRequest();
                monitorRequest.BizContent = build.BuildJson();
                result.response           = client.Execute(monitorRequest);
                return(result);
            }
            catch
            {
                result.response = null;
                return(result);
            }
        }
Example #20
0
        private void btnOrderStatus_Press(object sender, EventArgs e)
        {
            IAopClient client = GetAPOClient();
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();

            model.OutTradeNo = tradeNo;
            request.SetBizModel(model);
            //这是普通的接口使用Execute
            AlipayTradeQueryResponse response = client.Execute(request);

            //页面输出的response.Body就是orderString 可以直接给客户端请求,无需再做处理。
            System.Diagnostics.Debug.WriteLine(response.Body);
            MessageBox.Show(response.Body);
        }
Example #21
0
        public bool QueryNow()
        {
            IAopClient alipayClient = GetAopClient();
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
            AlipayTradeQueryModel   model         = new AlipayTradeQueryModel();

            model.OutTradeNo = Order.OrderNo;
            alipayRequest.SetBizModel(model);
            AlipayTradeQueryResponse response = alipayClient.Execute(alipayRequest);

            if (((string.Compare(response.TradeStatus, "TRADE_FINISHED") == 0 || string.Compare(response.TradeStatus, "TRADE_SUCCESS") == 0)))
            {
                var orderAmount = double.Parse(response.TotalAmount);
                if (Order.OrderAmount == orderAmount && string.Compare(Order.OrderNo, response.OutTradeNo) == 0)
                {
                    return(true);
                }
            }
            return(false);
        }
Example #22
0
        public void Precreate()
        {
            IAopClient client = GetClient();
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

            //TODO:此处替换官方文档
            request.BizContent = "{" +
                                 "    \"out_trade_no\":\"20160320010101001\"," +
                                 "    \"total_amount\":88.88," +
                                 "    \"discountable_amount\":8.88," +
                                 "    \"undiscountable_amount\":80," +
                                 "    \"buyer_logon_id\":\"15901825620\"," +
                                 "    \"subject\":\"Iphone6 16G\"," +
                                 "    \"body\":\"Iphone6 16G\"," +
                                 "    \"timeout_express\":\"90m\"," +
                                 "    \"sub_merchant\":{" +
                                 "      \"merchant_id\":\"19023454\"" +
                                 "    }" +
                                 "  }";

            request.BizContent = JsonConvert.SerializeObject(new Entities.Precreate()
            {
                out_trade_no = "20160320010101001",
                subject      = "Iphone6 16G",
                total_amount = 88.88
            });


            AlipayTradePrecreateResponse response = client.Execute(request);

            if (!response.IsError)
            {
                Console.WriteLine("调用成功");
            }
            else
            {
                Console.WriteLine("调用失败");
            }

            Assert.IsFalse(response.IsError);
        }
Example #23
0
        public Refund BuildRefund(Refund refund)
        {
            IAopClient alipayClient = GetAopClient();
            AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel   model         = new AlipayTradeRefundModel();

            model.OutTradeNo = refund.OrderNo;
            if (!string.IsNullOrEmpty(refund.TradeNo))
            {
                model.TradeNo = refund.TradeNo;
            }
            model.OutRequestNo = refund.OutRefundNo;
            model.RefundAmount = refund.RefundAmount.ToString();
            model.RefundReason = refund.RefundDesc;
            alipayRequest.SetBizModel(model);
            AlipayTradeRefundResponse response = alipayClient.Execute(alipayRequest);

            if (response.Code == "10000")
            {
                refund.TradeNo      = response.TradeNo;
                refund.RefundStatus = true;
            }
            return(refund);
        }
Example #24
0
        /// <summary>
        /// 支付宝扫码预支付
        /// </summary>
        /// <param name="precreate">支付实体</param>
        /// <param name="alipaySMPayBack">支付返回实体</param>
        /// <param name="message">错误提示</param>
        /// <returns></returns>
        internal bool Precreate(Precreate precreate, out PrecreateBack alipaySMPayBack, out string message)
        {
            _log.Info("扫码预支付 Precreate 开始");
            var payRequst = new AlipayTradePrecreateRequest();

            payRequst.SetNotifyUrl(AlipayConfig.NotifyUrl);
            precreate.Body = $"{precreate.DeviceID}║{precreate.Body}";
            //生成bizcontent的json数据,并把默认值除掉
            payRequst.BizContent = JsonConvert.SerializeObject(precreate, new Newtonsoft.Json.JsonSerializerSettings()
            {
                DefaultValueHandling = DefaultValueHandling.Ignore,
                ContractResolver     = new LowerPropertyContractResolver()
            }).ToLower();
            var payResponse = client.Execute(payRequst);

            if (payResponse.Code == "10000")
            {
                _log.Info("扫码预支付成功!");
                alipaySMPayBack = new PrecreateBack()
                {
                    Code         = payResponse.Code,
                    Msg          = payResponse.Msg,
                    Out_Trade_No = payResponse.OutTradeNo,
                    Sub_Code     = payResponse.SubCode,
                    Sub_Msg      = payResponse.SubMsg,
                    Qr_Code      = payResponse.QrCode
                };
                message = "";
                return(true);
            }
            else
            {
                alipaySMPayBack = null;
                message         = $"{ payResponse.Msg},{payResponse.SubMsg}";
                _log.Error($"扫码预支付失败:{message}");
                return(false);
            }
        }
Example #25
0
        public void Create()
        {
            IAopClient client = GetClient();
            AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();

            request.BizContent = "{" +
                                 "    \"out_trade_no\":\"20150320010101001\"," +
                                 "    \"seller_id\":\"2088102172273210\"," +
                                 "    \"total_amount\":88.88," +
                                 "    \"discountable_amount\":8.88," +
                                 "    \"undiscountable_amount\":80.00," +
                                 "    \"buyer_logon_id\":\"15901825620\"," +
                                 "    \"subject\":\"Iphone6 16G\"," +
                                 "    \"body\":\"Iphone6 16G\"," +
                                 "    \"buyer_id\":\"2088102146225135\"," +
                                 "      \"goods_detail\":[{" +
                                 "                \"goods_id\":\"apple-01\"," +
                                 "        \"alipay_goods_id\":\"20010001\"," +
                                 "        \"goods_name\":\"ipad\"," +
                                 "        \"quantity\":1," +
                                 "        \"price\":2000," +
                                 "        \"goods_category\":\"34543238\"," +
                                 "        \"body\":\"特价手机\"," +
                                 "        \"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
                                 "        }]," +
                                 "    \"operator_id\":\"Yx_001\"," +
                                 "    \"store_id\":\"NJ_001\"," +
                                 "    \"terminal_id\":\"NJ_T_001\"," +
                                 "    \"extend_params\":{" +
                                 "      \"sys_service_provider_id\":\"2088511833207846\"," +
                                 "      \"hb_fq_num\":\"3\"," +
                                 "      \"hb_fq_seller_percent\":\"100\"" +
                                 "    }," +
                                 "    \"timeout_express\":\"90m\"," +
                                 "    \"royalty_info\":{" +
                                 "      \"royalty_type\":\"ROYALTY\"," +
                                 "        \"royalty_detail_infos\":[{" +
                                 "                    \"serial_no\":1," +
                                 "          \"trans_in_type\":\"userId\"," +
                                 "          \"batch_no\":\"123\"," +
                                 "          \"out_relation_id\":\"20131124001\"," +
                                 "          \"trans_out_type\":\"userId\"," +
                                 "          \"trans_out\":\"2088101126765726\"," +
                                 "          \"trans_in\":\"2088101126708402\"," +
                                 "          \"amount\":0.1," +
                                 "          \"desc\":\"分账测试1\"," +
                                 "          \"amount_percentage\":\"100\"" +
                                 "          }]" +
                                 "    }," +
                                 "    \"alipay_store_id\":\"2016041400077000000003314986\"," +
                                 "    \"sub_merchant\":{" +
                                 "      \"merchant_id\":\"19023454\"" +
                                 "    }" +
                                 "  }";

            request.BizContent = JsonConvert.SerializeObject(new Entities.Create()
            {
                out_trade_no   = "20120320010101001",
                subject        = "Iphone 100",
                total_amount   = 8888.88,
                buyer_logon_id = "*****@*****.**",
            });


            AlipayTradeCreateResponse response = client.Execute(request);

            if (!response.IsError)
            {
                Console.WriteLine("调用成功");
            }
            else
            {
                Console.WriteLine("调用失败");
            }

            Assert.IsFalse(response.IsError);
        }
Example #26
0
        public AlipayF2FPayResult tradePay(AlipayTradePayContentBuilder builder)
        {
            AlipayF2FPayResult payResult = new AlipayF2FPayResult();

            try
            {
                AlipayTradePayRequest payRequest = new AlipayTradePayRequest();
                payRequest.BizContent = builder.BuildJson();
                AlipayTradePayResponse payResponse = client.Execute(payRequest);

                //payRequest.SetBizModel("");

                if (payResponse != null)
                {
                    switch (payResponse.Code)
                    {
                    case ResultCode.SUCCESS:
                        break;

                    //返回支付处理中,需要进行轮询
                    case ResultCode.INRROCESS:

                        AlipayTradeQueryResponse queryResponse = LoopQuery(builder.out_trade_no, 10, 3000);       //用订单号trade_no进行轮询也是可以的。
                        //轮询结束后还是支付处理中,需要调撤销接口
                        if (queryResponse != null)
                        {
                            if (queryResponse.TradeStatus == "WAIT_BUYER_PAY")
                            {
                                CancelAndRetry(builder.out_trade_no);
                                payResponse.Code = ResultCode.FAIL;
                            }
                            payResponse = toTradePayResponse(queryResponse);
                        }
                        break;

                    //明确返回业务失败
                    case ResultCode.FAIL:
                        break;

                    //返回系统异常,需要调用一次查询接口,没有返回支付成功的话调用撤销接口撤销交易
                    case ResultCode.ERROR:

                        AlipayTradeQueryResponse queryResponse2 = sendTradeQuery(builder.out_trade_no);

                        if (queryResponse2 != null)
                        {
                            if (queryResponse2.TradeStatus == TradeStatus.WAIT_BUYER_PAY)
                            {
                                AlipayTradeCancelResponse cancelResponse = CancelAndRetry(builder.out_trade_no);
                                payResponse.Code = ResultCode.FAIL;
                            }

                            payResponse = toTradePayResponse(queryResponse2);
                        }
                        break;

                    default:
                        payResult.response = payResponse;
                        break;
                    }
                    payResult.response = payResponse;
                    return(payResult);
                }
                else
                {
                    AlipayTradeQueryResponse queryResponse3 = sendTradeQuery(builder.out_trade_no);
                    if (queryResponse3 != null)
                    {
                        if (queryResponse3.TradeStatus == TradeStatus.WAIT_BUYER_PAY)
                        {
                            AlipayTradeCancelResponse cancelResponse = CancelAndRetry(builder.out_trade_no);
                            payResponse.Code = ResultCode.FAIL;
                        }
                        payResponse = toTradePayResponse(queryResponse3);
                    }
                    payResult.response = payResponse;
                    return(payResult);
                }
                //return payResult;
            }
            catch (Exception e)
            {
                AlipayTradePayResponse payResponse = new AlipayTradePayResponse();
                payResponse.Code   = ResultCode.FAIL;
                payResponse.Body   = e.Message;
                payResult.response = payResponse;
                return(payResult);
            }
        }
 public T Execute <T>(IAopRequest <T> request) where T : AopResponse
 {
     return(_aopClient.Execute(request));
 }
Example #28
0
        public ActionResult MicroPay(int?CompanyId, string storeId, string autoCode, string paySN, decimal totalPrice)
        {
            var op = new OpResult();
            AlipayTradePayResponse payResponse = null;

            try
            {
                var setting = paySetBLL.GetPaymentSettingBystoreId(1, storeId, CompanyId);
                client = new DefaultAopClient(qrcode._2.Config.serverUrl, setting.AppId, qrcode._2.Config.merchant_private_key, "", qrcode._2.Config.version,
                                              qrcode._2.Config.sign_type, qrcode._2.Config.alipay_public_key, qrcode._2.Config.charset);
                var           orderno = qrcode.wx.WxPayApi.GenerateOutTradeNo(setting.AppId);
                StringBuilder sb      = new StringBuilder();
                sb.Append("{\"out_trade_no\":\"" + orderno + "\",");
                sb.Append("\"scene\":\"bar_code\",");
                sb.Append("\"auth_code\":\"" + autoCode + "\",");
                sb.Append("\"total_amount\":\"" + totalPrice + "\",\"discountable_amount\":\"0.00\",");
                sb.Append("\"subject\":\"订单编号 " + paySN + "\",\"body\":\"\",");
                string expire_time = System.DateTime.Now.AddHours(1).ToString("yyyy-MM-dd HH:mm:ss");
                sb.Append("\"time_expire\":\"" + expire_time + "\"}");
                AlipayTradePayRequest payRequst = new AlipayTradePayRequest();
                payRequst.BizContent = sb.ToString();

                Dictionary <string, string> paramsDict = (Dictionary <string, string>)payRequst.GetParameters();
                payResponse = client.Execute(payRequst);
                switch (payResponse.Code)
                {
                case qrcode._2.ResultCode.SUCCESS:
                    op.Message   = payResponse.TradeNo;
                    op.Successed = true;
                    break;

                case qrcode._2.ResultCode.INRROCESS:
                    StringBuilder sb1 = new StringBuilder();
                    sb1.Append("{\"out_trade_no\":\"" + orderno + "\"}");

                    //返回支付处理中,需要进行轮询
                    AlipayTradeQueryResponse queryResponse = LoopQuery(sb1.ToString());
                    if (queryResponse != null)
                    {
                        op.Message   = queryResponse.TradeNo;
                        op.Successed = true;
                    }
                    else
                    {
                        var cancel1 = Cancel(sb1.ToString());
                        op.Message = cancel1.Code == qrcode._2.ResultCode.SUCCESS ? "订单支付失败,已撤销!" : (cancel1.SubMsg ?? cancel1.Msg);
                    }
                    break;

                case qrcode._2.ResultCode.FAIL:
                    StringBuilder sb2 = new StringBuilder();
                    sb2.Append("{\"out_trade_no\":\"" + orderno + "\"}");
                    Cancel(sb2.ToString());    //不撤销防止同订单号时产生退款
                    op.Message = payResponse.SubMsg ?? payResponse.Msg;
                    break;

                default:
                    op.Message = payResponse.SubMsg ?? payResponse.Msg;
                    break;
                }
            }
            catch (Exception ex)
            {
                op.Message = ex.Message;
                new Sys.LogEngine().WriteError("支付宝当面付失败!" + payResponse.Body, ex);
            }
            Pharos.Component.qrcode.Log.Debug(this.GetType().Name, "支付宝当面付,返回结果:" + payResponse.Body);
            return(new JsonNetResult(op));
        }
Example #29
0
        /// <summary>
        /// 查询订单状态
        /// </summary>
        /// <param name="request"></param>
        /// <param name="sceneryDomain"></param>
        /// <returns></returns>
        public QueryResponse Query(QueryRequest request, SceneryDomain sceneryDomain)
        {
            var result = false;

            //创建淘宝支付信息
            client = new DefaultAopClient(serverUrl, sceneryDomain.Apipay.APP_ID, sceneryDomain.Apipay.APP_PRIVATE_KEY, "", version,
                                          sign_type, sceneryDomain.Apipay.ALIPAY_PUBLIC_KEY, charset);

            QueryResponse queryResponse = new QueryResponse();
            StringBuilder biz_content   = new StringBuilder();

            biz_content.Append("{\"out_trade_no\":\"" + request.Out_trade_no + "\"}");


            AlipayTradeQueryRequest payRequst = new AlipayTradeQueryRequest();

            payRequst.BizContent = biz_content.ToString();

            Dictionary <string, string> paramsDict  = (Dictionary <string, string>)payRequst.GetParameters();
            AlipayTradeQueryResponse    payResponse = null;


            LogHelper.AlipayLog(string.Format("论寻-请求josn:{0}", biz_content));
            payResponse = client.Execute(payRequst);

            LogHelper.AlipayLog(string.Format("论寻-结果:{0}-{1}-{2}", payResponse.Code, payResponse.TradeStatus, payResponse.Body));
            if (string.Compare(payResponse.Code, ResultCode.SUCCESS, false) == 0)
            {
                if (payResponse.TradeStatus == "TRADE_FINISHED" ||
                    payResponse.TradeStatus == "TRADE_SUCCESS" ||
                    payResponse.TradeStatus == "TRADE_CLOSED")
                {
                    if (payResponse.TradeStatus == "TRADE_SUCCESS")
                    {
                        var detailDao = new AlipayDetailDao();
                        var qrCodeDao = new AlipayQRCodeDao();
                        Alipay_trade_query_response alipayDetail = JsonConvert.DeserializeObject <Alipay_trade_query_response>(payResponse.Body);
                        //需要检查数据库中是否有改数据 有的话 直接返回
                        var QRCodeDetail = qrCodeDao.IsExistOut_trade_no(alipayDetail.alipay_trade_query_response.Out_trade_no, alipayDetail.alipay_trade_query_response.Total_amount
                                                                         , sceneryDomain.Apipay.APP_ID);

                        if (result == null || QRCodeDetail.SceneryName == "-1")
                        {
                            LogHelper.AlipayLog("论寻:无通知参数");
                        }
                        //论寻:数据已经存在,不需要插入
                        if (QRCodeDetail.SceneryName != "-2")
                        {
                            //保存支付宝信息
                            string body = payResponse.Body;
                            alipayDetail.alipay_trade_query_response.SceneryName    = sceneryDomain.SceneryName;
                            alipayDetail.alipay_trade_query_response.Creater        = sceneryDomain.Apipay.APP_ID;
                            alipayDetail.alipay_trade_query_response.Updater        = "";
                            alipayDetail.alipay_trade_query_response.AppId          = sceneryDomain.Apipay.APP_ID;
                            alipayDetail.alipay_trade_query_response.BatchNumber    = QRCodeDetail.BatchNumber;
                            alipayDetail.alipay_trade_query_response.SceneryRate    = sceneryDomain.Rate;
                            alipayDetail.alipay_trade_query_response.AlipayPlayDate = Convert.ToDateTime(alipayDetail.alipay_trade_query_response.Send_pay_date.ToString("yyyy-MM-dd"));
                            detailDao.Add(alipayDetail.alipay_trade_query_response);
                        }
                        else
                        {
                            LogHelper.AlipayLog("论寻:数据已经存在,不需要插入");
                        }
                        queryResponse.buyer_logon_id = alipayDetail.alipay_trade_query_response.Buyer_logon_id;
                        queryResponse.gmt_payment    = alipayDetail.alipay_trade_query_response.Send_pay_date;
                        queryResponse.trade_no       = alipayDetail.alipay_trade_query_response.Trade_no;
                        result = true;
                    }
                }
            }

            if (result == false && request.IsLastRequest == 1)
            {
                var content = new StringBuilder();
                content.Append("{\"out_trade_no\":\"" + payResponse.OutTradeNo + "\"}");
                biz_content = content;
                Cancel(content.ToString());
            }
            return(queryResponse);
        }
Example #30
0
        private void BillDownloadurl(HttpContext context, IAopClient client, string adminHotelId, int hotelId, DateTime bill_date, string appAuthToken, AlipayDataDataserviceBillDownloadurlQueryRequest request)
        {
            try
            {
                string session = "";
                AlipayDataDataserviceBillDownloadurlQueryResponse response = client.Execute(request, session, appAuthToken);
                if (response != null && !string.IsNullOrEmpty(response.BillDownloadUrl))
                {
                    string url = response.BillDownloadUrl;//得到下载路径

                    string filename = HttpContext.Current.Server.MapPath("/File/Zip/AlipayBill.zip");
                    //使用WebClient 下载文件
                    System.Net.WebClient myWebClient = new System.Net.WebClient();
                    byte[] data   = myWebClient.DownloadData(url);
                    Stream stream = new MemoryStream(data);                                //byte[] 转换成 流
                    FileHelper.StreamToFile(stream, filename);                             //保存下载zip
                    string destinationFile = HttpContext.Current.Server.MapPath("/File/"); //解压路径
                    GZipHelper.UnZip(filename, destinationFile);                           //解压
                    string[] files = FileHelper.GetDirectoryFileList(destinationFile);

                    for (int i = 0; i < files.Length; i++)
                    {
                        string fn = files[i];

                        context.Response.Write("\r\n");
                        context.Response.Write(fn);
                        string    filePath = HttpContext.Current.Server.MapPath("/File/" + fn);//文件路径
                        DataTable dt       = GetdataFromCVS(filePath);
                        FileHelper.DeleteFile(filePath);
                        if (dt == null || dt.Rows.Count < 1)
                        {
                            continue;
                        }

                        context.Response.Write(".<br />");
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            if (fn.IndexOf("汇总") > 0)
                            {
                                Hashtable htStatistics = new Hashtable();
                                htStatistics["AdminHotelId"] = adminHotelId;
                                htStatistics["HotelId"]      = hotelId;
                                htStatistics["Bill_Date"]    = bill_date.ToString("yyyy-MM-dd");
                                htStatistics["PaySource"]    = 2;

                                htStatistics["Transaction_Number"] = dt.Rows[k]["交易订单总笔数"].ToString();  //总交易单数
                                htStatistics["Transaction_Money"]  = dt.Rows[k]["订单金额(元)"].ToString();  //总交易额
                                htStatistics["Refund_Money"]       = dt.Rows[k]["退款订单总笔数"].ToString();  //总退款金额
                                htStatistics["Vouchers_Discounts"] = dt.Rows[k]["支付宝优惠(元)"].ToString(); //总代金券或立减优惠退款金额
                                htStatistics["Service_Charge"]     = dt.Rows[k]["服务费(元)"].ToString();   //手续费总金额
                                DataFactory.SqlDataBase().InsertByHashtable("Hotel_Bill_Total", htStatistics);
                            }
                            else
                            {
                                Hashtable ht = new Hashtable();
                                ht["AdminHotelId"] = adminHotelId;
                                ht["HotelId"]      = hotelId;
                                ht["Bill_Date"]    = bill_date.ToString("yyyy-MM-dd");
                                ht["PaySource"]    = 2;

                                ht["Transaction_Time"] = dt.Rows[k]["完成时间"].ToString();                                  //交易时间
                                ht["Appid"]            = dt.Rows[k]["商品名称"].ToString();                                  //公众账号ID
                                ht["Mch_Id"]           = dt.Rows[k]["门店编号"].ToString();                                  //商户号
                                ht["Sub_Mch_Id"]       = dt.Rows[k]["门店名称"].ToString();                                  //子商户号
                                ht["Device_Number"]    = dt.Rows[k]["终端号"].ToString();                                   //设备号
                                ht["WX_Order_Numbe"]   = dt.Rows[k]["支付宝交易号"].ToString();                                //微信订单号
                                ht["Order_Numbe"]      = dt.Rows[k]["商户订单号"].ToString();                                 //商户订单号
                                ht["Openid"]           = dt.Rows[k]["对方账户"].ToString();                                  //用户标识
                                ht["Transaction_Type"] = dt.Rows[k]["商品名称"].ToString() == "扫码支付" ? "MICROPAY" : "JSAPI"; //交易类型
                                if (dt.Rows[k]["业务类型"].ToString().IndexOf("退款") >= 0)
                                {
                                    ht["Transaction_State"]         = "REFUND";                                                      //交易状态
                                    ht["Total_Money"]               = "0.00";                                                        //总金额
                                    ht["Refund_Money"]              = CommonHelper.GetDouble(dt.Rows[k]["订单金额(元)"].ToString()) * -1; //退款金额
                                    ht["WX_Refund_Numbe"]           = dt.Rows[k]["支付宝交易号"].ToString();                               //微信退款单号
                                    ht["Refund_Numbe"]              = dt.Rows[k]["商户订单号"].ToString();                                //商户退款单号
                                    ht["Refund_Type"]               = "ORIGINAL";                                                    //退款类型
                                    ht["Refund_State"]              = "SUCCESS";                                                     //退款状态
                                    ht["Refund_Vouchers_Discounts"] = dt.Rows[k]["支付宝优惠(元)"].ToString();                             //代金券或立减优惠退款金额
                                }
                                else
                                {
                                    ht["Transaction_State"] = "SUCCESS";                                                 //交易状态
                                    ht["Total_Money"]       = dt.Rows[k]["订单金额(元)"].ToString();                          //总金额
                                    ht["Refund_Money"]      = "0.00";                                                    //退款金额
                                }
                                ht["Paying_Bank"]        = "";                                                           //付款银行
                                ht["Currency_Type"]      = "CNY";                                                        //货币种类
                                ht["Data_Package"]       = "";                                                           //商户数据包
                                ht["Vouchers_Discounts"] = dt.Rows[k]["支付宝优惠(元)"].ToString();                            //代金券或立减优惠金额
                                ht["Commodity_Name"]     = dt.Rows[k]["商品名称"].ToString();                                //商品名称
                                ht["Service_Charge"]     = CommonHelper.GetDouble(dt.Rows[k]["服务费(元)"].ToString()) * -1; //手续费
                                ht["Fee_Rate"]           = "0.60%";                                                      //费率
                                DataFactory.SqlDataBase().InsertByHashtable("Hotel_Bill", ht);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }