C#调用支付宝接口案例

C#调用支付宝接口案例

        /// 
        /// 页面跳转同步通知页面
        /// 
        /// 
        public ActionResult PayResult()
        {
            SortedDictionary<string, string> sPara = GetRequestGet();
            T_Trade objTrade = null;
            if (sPara.Count > 0)//判断是否有带返回参数
            {
                Notify aliNotify = new Notify();
                bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);
                if (verifyResult)//验证成功
                {
                    //商户订单号
                    string out_trade_no = Request.QueryString["out_trade_no"];

                    //支付宝交易号
                    string trade_no = Request.QueryString["trade_no"];

                    //交易状态
                    string trade_status = Request.QueryString["trade_status"];

                    //验证订单状态并处理业务逻辑
                    VerifyPay(out_trade_no, trade_no, trade_status);
                    var db = DBHelper.QueryDB();
                    string strSql = string.Format(@"select * from T_Trade where ID='{0}'", out_trade_no);
                    objTrade = db.Sql(strSql).QuerySingle();
                    strSql = string.Format(@"select UserName from T_User where ID={0}", objTrade.UserID);
                    ViewBag.UserName = db.Sql(strSql).QuerySingle<string>();
                }
            }
            return View(objTrade);
        }
 ///    
        /// 服务器异步通知页面
        /// 
        /// 
        [AllowAnonymous]
        public ActionResult PayNotify()
        {
            SortedDictionary<string, string> sPara = GetRequestPost();
            if (sPara.Count > 0)//判断是否有带返回参数
            {
                Notify aliNotify = new Notify();
                bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]);
                if (verifyResult)//验证成功
                {
                    //商户订单号
                    string out_trade_no = Request.Form["out_trade_no"];

                    //支付宝交易号
                    string trade_no = Request.Form["trade_no"];

                    //交易状态
                    string trade_status = Request.Form["trade_status"];

                    //验证订单状态并处理业务逻辑
                    VerifyPay(out_trade_no, trade_no, trade_status);

                    Response.Write("success");  //请不要修改或删除
                }
                else//验证失败
                {
                    Response.Write("fail");
                }
            }
            else
            {
                Response.Write("无通知参数");
            }
            return View();
        }
        public bool VerifyPay(string strOutTradeNo, string strTradeNo, string strTradeStatus)
        {
            bool bRes = false;
            string strSql = string.Format(@"select * from T_Trade where ID='{0}'", strOutTradeNo);
            T_Trade objTrade = DBHelper.QueryDB().Sql(strSql).QuerySingle();
            if (strTradeStatus == "TRADE_FINISHED" || strTradeStatus == "TRADE_SUCCESS")
            {
                if (objTrade.State != 2)
                {
                    objTrade.TradeNo = strTradeNo;
                    objTrade.FinishTime = DateTime.Now;
                    objTrade.State = 2;
                    doPay(objTrade);
                }
                bRes = true;
            }
            else if (strTradeStatus == "TRADE_CLOSED")
            {
                if (objTrade.State != 1)
                {
                    objTrade.TradeNo = strTradeNo;
                    objTrade.FinishTime = DateTime.Now;
                    objTrade.State = 1;
                    doPay(objTrade);
                }
                bRes = false;
            }
            return bRes;
        }
        /// 
        /// 获取支付宝GET过来通知消息,并以“参数名=参数值”的形式组成数组
        /// 
        /// request回来的信息组成的数组
        public SortedDictionary<string, string> GetRequestGet()
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.QueryString;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
            }

            return sArray;
        }

        /// 
        /// 获取支付宝POST过来通知消息,并以“参数名=参数值”的形式组成数组
        /// 
        /// request回来的信息组成的数组
        public SortedDictionary<string, string> GetRequestPost()
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.Form;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
            }

            return sArray;
        }       
        /// 
        /// 提交支付请求到支付宝
        /// 
        public ActionResult PostToAlipay(int id)
        {
            int uid = id;

            var db = DBHelper.QueryDB();
            string strSql = string.Format(@"select count(ID) from T_Trade where UserID={0} and State=2", uid);
            //如果已经支付过则跳转到首页
            if (db.Sql(strSql).QuerySingle<int>() > 0)
            {
                return Redirect("/home");
            }
            //查找没有支付的订单
            strSql = string.Format(@"select * from T_Trade where UserID={0} and State=0", uid);
            var objTrade = db.Sql(strSql).QuerySingle();

            //支付类型,1为商品购买
            string payment_type = "1";

            //服务器异步通知页面路径,需http://格式的完整路径,不能加?id=123这类自定义参数
            string notify_url = "http://zc.jcxt99.com/pay/paynotify";
            //string notify_url = "http://192.168.1.33:39371/pay/paynotify";

            //页面跳转同步通知页面路径,需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/
            string return_url = "http://zc.jcxt99.com/pay/payresult";
            //string return_url = "http://192.168.1.33:39371/pay/payresult";

            //商户订单号,商户网站订单系统中唯一订单号,必填
            string out_trade_no = objTrade == null ? Guid.NewGuid().ToString("N").Trim() : objTrade.ID;

            //订单名称,必填
            string subject = "会员资格";

            //付款金额,必填
            string total_fee = "200.00";
            //string total_fee = "0.01";

            string it_b_pay = "30m";

            //防钓鱼时间戳,若要使用请调用类文件submit中的query_timestamp函数
            //string anti_phishing_key = Com.Alipay.Submit.Query_timestamp();

            //客户端的IP地址,非局域网的外网IP地址,如:221.0.0.1
            //string exter_invoke_ip = "";

            //把请求参数打包成数组
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("partner", Config.Partner);
            sParaTemp.Add("seller_email", Config.Seller_email);
            sParaTemp.Add("_input_charset", Config.Input_charset.ToLower());
            sParaTemp.Add("service", "create_direct_pay_by_user");
            sParaTemp.Add("payment_type", payment_type);
            sParaTemp.Add("notify_url", notify_url);
            sParaTemp.Add("return_url", return_url);
            sParaTemp.Add("out_trade_no", out_trade_no);
            sParaTemp.Add("subject", subject);
            sParaTemp.Add("total_fee", total_fee);
            sParaTemp.Add("it_b_pay", it_b_pay);
            //sParaTemp.Add("body", body);
            //sParaTemp.Add("show_url", show_url);
            //sParaTemp.Add("anti_phishing_key", anti_phishing_key);
            //sParaTemp.Add("exter_invoke_ip", exter_invoke_ip);

            //建立请求
            string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认");
            if (objTrade == null)
            {
                objTrade = new T_Trade();
                objTrade.ID = out_trade_no;
                objTrade.UserID = uid;
                objTrade.TradeTime = DateTime.Now;
                objTrade.Value = total_fee;
                objTrade.TradeNo = "";
                objTrade.FinishTime = DateTime.Now;
                objTrade.State = 0;
                if (db.Insert("T_Trade", objTrade).AutoMap().Execute() > 0)
                {
                    Response.Write(sHtmlText);
                }
                else
                {
                    return Content("生成订单失败,请刷新页面重试!");
                }
            }
            else
            {
                Response.Write(sHtmlText);
            }
            return null;
        }

你可能感兴趣的:(c#)