轻源码

  • QingYuanMa.com
  • 全球最大的互联网技术和资源下载平台
搜索
一起源码网 门户 支付接口开发 查看主题

支付宝二维码API的实现和文档

发布者: kkkk | 发布时间: 2018-3-5 03:44| 查看数: 3474| 评论数: 1|帖子模式

1、首先。我们清楚既然是API,那必然有文档。在这里我会贴出我与alipayCoder一遍联调一边写的文档(在原著上进行修改的)。这里我先把文档贴出。请大家仔细看。

文档下载地址:

总结:

1、生成二维码的步骤(根据你的ID和key(支付宝的授权) + 生成二维码的参数列表拼接字符串)(字符串的拼接说明:拼接成URL。1、key (参数名)+ “=” + value(参数值)按照key.a-z的排序2、拼接排序后的结果例如:bizname="黄翔"&return_url="returnUrl.asxp"(我这里只举例2个参数.详情看API文档)进行编码例如:utf-8获得URL地址。3、将生成的URL地址 + key = “keyvalue”(你的key)进行MD5加密获得sign。4、将完整的url连接:带http://进行模拟请求。5、获得模拟请求结果(在当前页面、会返回xml数据。这里对xml数据解析保存至服务器或你的txt文本。方便以后调用。)6、根据返回的二维码进行图片生成(网上很多的二维码生成DLL。如果需要可以联系我QQ:1434197610.))7、就是你们运营的使用了。大致讲完。有什么不明白的留言吧。这里我还是将我的代码贴出.草稿代码哈。别批我。呵呵呵

新增二维码操作代码部分:

<p>
	<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Collections;
using System.Data;
using System.Xml;
using System.Security.Cryptography;
using ThoughtWorks.QRCode.Codec;
using System.IO;

namespace TopAPIDemo
{
    /// <summary>
    /// 新增二维码产品
    /// </summary>
    public partial class WebForm1 : System.Web.UI.Page
    {
        //string tmp = "";
        //API入口
        string url = "";
        //加密类型
        string sign_type = "sign_type=MD5";
        //联测key
        //自我开发测试key
        //正式key
        string key = "";
        //合作商户ID。授权标识
        string partnerKey = "partner"; string partnerValue = "";  //正式PID //string partnerValue = "";test PID:
        //编码格式
        string _input_charsetKey = "_input_charset"; string _input_charsetValue = "UTF-8";
        //二维码。这里保存二维码地址
        string qrcodeKey = null; string qrcodeValue = null;
        //API输入参数签名结果
        string sign = null;
        //指示调用函数
        string serviceMethodKey = "service"; string serviceMethodValue = "alipay.mobile.qrcode.create";

        //二维码操作方式
        string methodKey = "method"; string methodValue = MethodType.MethodType_add;
  
        //收款方支付宝账号(手机号码或者邮箱地址)。当method=add时不可空
        string recevie_accountKey = "recevie_account"; string recevie_accountValue = "alipay-test12@alipay.com"; //正式账号:

        //收款方名称(收款方在手机上显示的名称)。当method=add时不可空
        string recevie_account_nameKey = "recevie_account_name"; string recevie_account_nameValue = "通吃网";

        //订单名称编号(商品名称).获得平台自身数据进行数据赋值接入当method=add时不可空。
        string biz_nameKey = "biz_name"; //string biz_nameValue = "重庆特产奉节脐橙10公斤包邮 纯绿色脐橙(公益项目,请单独购买)23号发货";//值从文本狂获取

        //交易默认金额,交易默认金额,以元为单位。格式为:xx.xx,小数点后保留两位小数,如19.71。当method=add时不可空。
        string biz_amountKey = "biz_amount"; //string biz_amountValue = "0.10";//对应键的值根据业务规则从数据查询获取

        //交易金额列表。格式必须为:{title}|{name1,name2..}|{value1,value2..}当method=add时不可空。通过具体的商品来进行操作
        string biz_amount_listKey = "biz_amount_list"; string biz_amount_listValue = "{优惠}|{特惠价}|{00.10}";

        //商户生成二维码且用户使用了二维码,创建了一笔交易,支付宝通过该路径通知商户系统下订单。如果为空则不通知商户系统。
        string return_urlKey = "return_url"; string return_urlValue = "http://" + HttpContext.Current.Request.Url.Host.ToString() + "/return_url.aspx";//return_url.aspx

        //支付成功后,支付宝通过该路径通知商户支付成功,同时获取商户商品信息。如果为空则不通知商户系统。
        string notify_urlKey = "notify_url"; string notify_urlValue = "http://" + HttpContext.Current.Request.Url.Host.ToString() + "/notify_url.aspx";

        //业务类型。值为:1:商品购买 2:我要付款
        //商品购买是指用户通过拍摄二维码购买某种商品,如购买游戏点卡;
        //我要付款是指用户拍摄二维码直接向另一用户付款。
        string biz_typeKey = "biz_type"; string biz_typeValue = "";

        //用户拍摄二维码后在支付宝客户端显示的商品的可选数量列表,格式为:{count1,count2..}.例:{1,2,3,4,5}.该列表通过数据库获得商品库存来进行填充
        string biz_count_listKey = "biz_count_list"; string biz_count_listValue = "{1,2,3,4,5}";

        //交易类型1:即时到账我要收款交易2:即时到账我要付款交易3:担保交易。默认值为1
        string trade_typeKey = "trade_type"; string trade_typeValue = "1";

        //是否需要收获地址
        string need_addressKey = "need_address"; string need_addressValue = "T"; 

        //如果用户超过该时间不支付,则该交易关闭。单位为分钟,取值范围为5~60。默认为5分钟。
        string pay_timeoutKey = "pay_timeout"; string pay_timeoutValue = "5";

        //1:不带订单名称(对应于biz_name属性)的二维码2:带订单名称(对应于biz_name属性)的二维码默认为1。
        string qrcode_styleKey = "qrcode_style"; string qrcode_styleValue = "2";

        string memoKey = "memo"; string memoValue = "通吃网零食真好吃";

        protected void Page_Load(object sender, EventArgs e)
        {   
            
        }   

        /// <summary>
        /// 新增二维码产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnCreate_Click(object sender, EventArgs e)
        {
            mt.Model.Products pro = null;
            string tmptxt = TextBox1.Text;
            if (tmptxt.Trim() != "")   
            {
                pro = new mt.BLL.Products().GetModel(TextBox1.Text);   //获得产品信息
                if (pro != null)                                       //对输入的产品名进行非null验证
                {
                    QREnty enty = new QREnty();
                    enty.ProductID = pro.ProductID;
                    enty.ProductName = pro.ProductName;
                    //验证需要生产二维码的商品是否曾经已经生成
                    if (this.GetQRCodeByProductName(enty))//
                    {
                        //向支付宝请求创建二维码并获得二维码条根据它创建二维码图片和数据信息(XML)保存至本地服务器
                        if (CreateQrcodeImgByAplieQrcode(enty, pro))
                        {
                            enty.ImgUrl = ViewState["imgUrl"] != null ? ViewState["imgUrl"].ToString() : "";
                            enty.QRCode = ViewState["QrCode"] != null ? ViewState["QrCode"].ToString() : "";
                            if (this.SaveQRCodeByXML(enty))
                            {
                                Image1.ImageUrl = enty.ImgUrl;
                                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "yes", "alert('恭喜,新增二维码产品成功');", true);
                            }
                            else { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "errosql", "alert('二维码产品保存至数据库失败');", true); }
                        }
                        else
                        {
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "erroQR", "alert('生成二维码产品失败');", true);
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "erroExits", "alert('当前产品已经是二维码产品')", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "erroNothingPro", "alert('没有该产品,请重新输入')", true);
                }
            }
            else { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "erroNothing", "alert('产品名不能为空')", true); }
        }

        /// <summary>
        /// 根据产品名模糊搜索二维码产品信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnSeeImage_Click(object sender, EventArgs e)
        {
            string tmp = TextBox1.Text.Trim();
            if (tmp != "")
            {
                QREnty enty = new QREnty();
                enty.ProductName = tmp;
                QREntyDAL dal = new QREntyDAL();
                enty = dal.GetModel(enty, 2);
                if (enty != null)
                {
                    Image1.ImageUrl = enty.ImgUrl;
                }
                else { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "errosqlnodataSourseObj", "alert('没有该信息,请重新输入检索')", true); }

            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "errosqlnodataSourse", "alert('文本框为空,请重新输入检索')", true);
            }
        }

        #region 本地数据库操作  新增二维码产品,验证产品是否已经是二维码产品  处理步骤五
        /// <summary>
        ///  将请求的来的数据信息保存
        /// </summary>
        bool SaveQRCodeByXML(QREnty enty)
        {
            QREntyDAL dal = new QREntyDAL();
            if (dal.Add(enty) > 0)
            {
                return true;
            }
            this.WrtieLogSign("ADDSQLErro", "将生成的二维码信息保存至服务器数据库失败");
            return false;
        }

        /// <summary>
        /// 通过要生成的产品名称去检查当前生成商品是否已经存在
        /// </summary>
        /// <returns>true为不存在</returns>
        bool GetQRCodeByProductName(QREnty entytmp)
        {
            QREntyDAL dal = new QREntyDAL();

            if (dal.GetModel(entytmp, 2) == null)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region 根据支付宝回传的二维码ID生成相关产品图片 处理步骤四
        /// <summary>
        /// 根据支付宝回传的二维码ID生成相关产品图片并向数据库进行信息添加
        /// </summary>
        /// <param name="enty">实体信息</param>
        /// <returns>bool。为true成功</returns>
        bool CreateQrcodeImgByAplieQrcode(QREnty enty, mt.Model.Products pro)
        {
            enty.QRCode = this.xmlGetQrcodeImgByAplieQrcode(this.GetRequestUrl(pro));
            if (enty.QRCode != null)
            {
                ViewState.Add("QrCode", enty.QRCode);
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                try
                {
                    //int scale = Convert.ToInt16(Request["Txtsize"].ToString());
                    //指定生成二维码图片大小
                    qrCodeEncoder.QRCodeScale = 4;
                    //指定生成方式
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    #region 本版号指定,二维码纠错能力指定 其他的二维码图片生成模式
                    //try  指定版本号
                    //{
                    //    int version = Convert.ToInt16(Request["DDLVer"].ToString());
                    //    qrCodeEncoder.QRCodeVersion = version;
                    //}
                    //catch (Exception ex)
                    //{
                    //    return false;
                    //}
                    //string errorCorrect = Request["DDLJC"].ToString();
                    //if (errorCorrect == "L")
                    //    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
                    //else if (errorCorrect == "M")
                    //    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    //else if (errorCorrect == "Q")
                    //    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
                    //else if (errorCorrect == "H")暂定为最高级的纠错能力

                    //String encoding = Request["DDLEncode"].ToString();
                    //if (encoding == "Byte")
                    //{
                    //    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    //}
                    //else if (encoding == "AlphaNumeric")
                    //{
                    //    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
                    //}
                    //else if (encoding == "Numeric")
                    //{
                    //    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
                    //}
                    #endregion

                    #region 开始生成二维码
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
                    String data = enty.QRCode;
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    System.Drawing.Image myimg = qrCodeEncoder.Encode(data);
                    myimg.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                    myimg = System.Drawing.Image.FromStream(ms);
                    string address = Server.MapPath("QRImage") + "\\" + enty.QRCode.Replace(":", "").Replace("[", "").Replace("]", "") + ".gif";
                    myimg.Save(address);
                    ViewState.Add("imgUrl", "QRImage/" + enty.QRCode.Replace(":", "").Replace("[", "").Replace("]", "") + ".gif");
                    //进行数据库操作
                    return true;
                    //将生成的图片输出
                    //Response.ClearContent();
                    //Response.ContentType = "image/Gif";
                    //Response.BinaryWrite(ms.ToArray());
                    //Response.End();

                    #endregion

                }
                catch (Exception ex)
                {
                    this.WrtieLogSign("CreateImgByQRCode", "根据二维码字符串创建二维码图片失败");
                    return false;
                }

            }
            this.WrtieLogSign("NoQRCodeByParamerters", "根据二维码字符串创建二维码图片失败");
            return false;
        }

        #endregion 

        #region 模拟请求,获得二维码数据 处理步骤三
        /// <summary>
        /// 通过请求拼接的URL地址获取相关XML数据
        /// </summary>
        /// <param name="httpUrl">请求地址</param>
        /// <returns>二维码号码</returns>
        public string xmlGetQrcodeImgByAplieQrcode(string httpUrl)
        {
            string xmlPath = httpUrl; // 该地址不能包含中文
            DataSet ds = new DataSet();
            WebClient wc = new WebClient();
            //对请求地址的数据开始进行下载
            byte[] bt = wc.DownloadData(xmlPath);
            string source = Byte2String(bt);
            //加载请求xml中的相关产品信息数据
            XmlControl xd = new XmlControl(xmlPath, XmlControl.enumXmlPathType.AbsolutePath);
            string boolIs_success = xd.GetXmlNodeValue("alipay/is_success");
            if (boolIs_success.ToLower() == "t")
            {
                string tmpCode = xd.GetXmlNodeValue("alipay/response/createQrcode/qrcode");
                return tmpCode;
            }
            this.WrtieLogSign("QRCodeCreateErro","请求获得二维码字符串失败");
            return null;
        }

        /// <summary>
        /// 进行字符串编码
        /// </summary>
        /// <param name="bt"></param>
        /// <returns></returns>
        public static string Byte2String(byte[] bt)
        {
            System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("UTF-8");
            string str = encoding.GetString(bt);
            return str;
        }


        //交易安全验证码zpdjh9ywq433ejjnkrbc5pys7ipkosnz

        #endregion

        #region 新增二维码URL地址处理 处理步骤二
        /// <summary>
        /// 新增二维码URL地址处理
        /// </summary>
        /// <param name="pro">产品实体</param>
        /// <returns>发起请求的URL</returns>
        public string GetRequestUrl(mt.Model.Products pro)
        {
            if (pro != null)
            {
                Dictionary<string, string> dicArray = new System.Collections.Generic.Dictionary<string, string>();
                dicArray.Add(partnerKey, partnerValue);
                dicArray.Add(_input_charsetKey, _input_charsetValue);
                dicArray.Add(serviceMethodKey, serviceMethodValue);
                dicArray.Add(methodKey, methodValue);
                dicArray.Add(recevie_account_nameKey, recevie_account_nameValue);
                dicArray.Add(recevie_accountKey, recevie_accountValue);
                dicArray.Add(biz_nameKey, pro.ProductName);
                dicArray.Add(biz_amountKey, (pro.ProductType == 4 ? pro.PriceOriginal : pro.Price).ToString());
                dicArray.Add(biz_amount_listKey, (pro.ProductType == 4 ? "{优惠}|{特惠价}|{" + pro.PriceOriginal + "}" : "{零售价}|{最低零售价}|{" + pro.Price + "}"));
                dicArray.Add(return_urlKey, return_urlValue);
                dicArray.Add(notify_urlKey, notify_urlValue);
                dicArray.Add(need_addressKey, need_addressValue);
                //dicArray.Add(qrcode_styleKey,qrcode_styleValue);
                //dicArray.Add(memoKey,memoValue);
                //开始进行排序
                //dicArray = AlipayClass.AlipayFunction.Para_filter(dicArray);
                //获得参数请求地址
                string urlTmpLink = AlipayClass.AlipayFunction.Create_linkstring_urlencode(dicArray);
                //生成签名
                sign = "sign=" + this.GetMySign(pro);
                //拼接请求地址
                string tmpppp = url + urlTmpLink + sign + "&" + sign_type;
                this.WrtieLogSign("postUrl", tmpppp);
                //将请求地址返回
                return tmpppp;
            }
            //产生产品信息实体为空的日志
            this.WrtieLogSign("ProductIsNull", "‘新增二维码URL地址处理’方法内产品实体信息为空");
            return null;
        }
        #endregion

        #region   获得签名证书  处理步骤一

        public string GetMySign(mt.Model.Products pro)
        {
            int i;
            string[] Oristr ={ 
                partnerKey + "="+ partnerValue, 
                _input_charsetKey + "=" + _input_charsetValue, 
                serviceMethodKey + "=" + serviceMethodValue, 
                methodKey + "=" + methodValue, 
                recevie_account_nameKey + "=" + recevie_account_nameValue, 
                recevie_accountKey + "=" + recevie_accountValue, 
                biz_nameKey + "=" + pro.ProductName,  
                biz_amountKey + "=" + (pro.ProductType == 4 ? pro.PriceOriginal : pro.Price).ToString(), 
                biz_amount_listKey + "=" + (pro.ProductType == 4 ? "{优惠}|{特惠价}|{" + pro.PriceOriginal + "}" : "{零售价}|{最低零售价}|{" + pro.Price + "}"),
                return_urlKey + "=" + return_urlValue,
                notify_urlKey + "=" + notify_urlValue,
                need_addressKey + "=" + need_addressValue
                //memoKey,memoValue
                };

            //进行排序;
            string[] Sortedstr = BubbleSort(Oristr);


            //构造待md5摘要字符串 ;

            System.Text.StringBuilder prestr = new System.Text.StringBuilder();

            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr.Append(Sortedstr[i]);
                }
                else
                {
                    prestr.Append(Sortedstr[i] + "&");
                }
            }
            prestr.Append(key);
            WrtieLogSign("prestr", prestr.ToString());
            //生成Md5摘要;
            string sign = GetMD5(prestr.ToString(), "UTF-8");
            WrtieLogSign("sign", sign);
            //以下是POST方式传递参数
            return sign;
        }

        /// <summary>
        /// 冒泡排序法
        /// </summary>
        public static string[] BubbleSort(string[] r)
        {
            int i, j; //交换标志 
            string temp;

            bool exchange;

            for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序 
            {
                exchange = false; //本趟排序开始前,交换标志应为假

                for (j = r.Length - 2; j >= i; j--)
                {//交换条件
                    if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0)
                    {
                        temp = r[j + 1];
                        r[j + 1] = r[j];
                        r[j] = temp;

                        exchange = true; //发生了交换,故将交换标志置为真 
                    }
                }

                if (!exchange) //本趟排序未发生交换,提前终止算法 
                {
                    break;
                }
            }
            return r;
        }


        /// <summary>
        /// 与ASP兼容的MD5加密算法
        /// </summary>
        public static string GetMD5(string s, string _input_charset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding(_input_charset).GetBytes(s));
            System.Text.StringBuilder sb = new System.Text.StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }

        #endregion

        /// <summary>
        /// 日志生成
        /// </summary>
        /// <param name="txtName">日志生成文件名</param>
        /// <param name="content">日志生成内容</param>
        public void WrtieLogSign(string txtName, string content)
        {
            String rootPath = Server.MapPath("/CreateLog");
            string tmpTime = DateTime.Now.ToString().Replace(":", "").Replace("-", "").Replace("_", "").Replace("/", "");
            File.WriteAllText(rootPath + "/" + tmpTime + txtName + ".txt", tmpTime + ":" + content, System.Text.Encoding.UTF8);
        }
    }
}</pre>

页面部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TopAPIDemo.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        请输入新增二维码产品的产品名<asp:TextBox ID="TextBox1" runat="server" 
            Width="408px"></asp:TextBox>
        <asp:Button ID="BtnCreate" runat="server" Text="开始生成二维码" 
            onclick="BtnCreate_Click" />
        <asp:Button ID="BtnSeeImage" runat="server" Text="根据产品名查看对应的二维码" 
            onclick="BtnSeeImage_Click" />
    
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
    
        <br />
        <asp:Image ID="Image1" runat="server"  />
    
    </div>
    </form>
</body>
</html>


returnl页面源码(页面部空的):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using AlipayClass;
using System.Net;
using System.Text;
using System.IO;
using mt.Model;
using mt.WebUnits;
using mt.DB;
using mt.DAL;
using mt.BLL;
using System.Collections;
using System.Data;
using System.Security.Cryptography;

namespace TopAPIDemo
{
    public partial class return_url : System.Web.UI.Page
    {
        //{result:1,outTradeNo:1234567890,money:56.50,memo:成功}
        //{result:-1,memo:失败}
         

        mt.Model.Products Mtproduct = null;

        Dictionary<string, string> dic = null;

        protected void Page_Load(object sender, EventArgs e)
        {

            File.WriteAllText(Server.MapPath("~") + "1111111111111.txt", "程序开始执行", System.Text.Encoding.UTF8);

                dic = new Dictionary<string, string>();
                //获得相关post参数
                dic = GetRequestPost(dic);
                if (ValidateSign())
                {
                    this.WriteMemeryString();
                }
                else 
                {
                   string tmpStr = "{result:-1,memo:失败}";
                   File.WriteAllText(Server.MapPath("~") + "ResultRepose.txt", tmpStr, System.Text.Encoding.UTF8);
                   Response.Write(tmpStr);
                   Response.Flush();
                }
        }

        //#region 订单添加

        ///// <summary>
        ///// 通过支付宝通知过来的客户下单二维码和产品名称获取相关产品信息生成订单,并且将该订单在系统自身生成
        ///// </summary>
        ///// <returns></returns>
        //bool InsertOrdersByQRcode(mt.Model.Products product)
        //{
        //    try
        //    {
        //        if (product.ProductName != null)
        //        {

        //        }
        //        string OrderMsg = "";
        //        mt.Model.Orders orderModel = setOrder(out OrderMsg);

        //        //检查信息是否有效
        //        if (orderModel == null || OrderMsg.Length > 0)
        //        {
        //            lblOrderMsg.Text = "填写信息有误:<br/>" + OrderMsg;
        //            ScriptManager.RegisterStartupScript(Page, this.GetType(), "click", "divErrorMsg();", true);
        //            return;
        //        }

        //        int tongchiCardId = mt.WebUnits.DataOperater.StrToInt(hidTcTCK.Value);
        //        tongchiCardId = mt.WebUnits.DataOperater.StrToInt(hidTcYHQ.Value);
        //        //int tongchiAmount = mt.WebUnits.DataOperater.StrToInt(txtTongchiCard.Text);

        //        //准备参数
        //        int orderId = -1;


        //        //创建为空的一个商品
        //        mt.Model.Products productModel = new mt.Model.Products();
        //        mt.BLL.Products productManager = new mt.BLL.Products();
        //        List<mt.Model.OrderItems> itemList = new List<mt.Model.OrderItems>();
        //        List<mt.Model.Products> productList = new List<mt.Model.Products>();

        //        for (int i = 0; i < cartList.Count; i++)
        //        {
        //            //将购物车里的商品拆解为单个订单
        //            mt.Model.OrderItems itemModel = cartForOrder.CartForOrderItems(cartForOrder.mt_buyCartForBuyCart(cartList[i]), orderId);
        //            //将单个订单放入订单集
        //            itemList.Add(itemModel);

        //            //通过购物车里的商品编号获得对应的单个商品
        //            productModel = productManager.GetModel(cartList[i].productID);
        //            //调整当前在订单里的商品的被订数
        //            productModel.OrderNum = productModel.OrderNum + int.Parse(itemModel.Amount.ToString());
        //            //将单个商品放入商品集
        //            productList.Add(productModel);
        //        }
        //        string msg = "";

        //        //int youhuiId = mt.WebUnits.DataOperater.StrToInt(hidTcYHQ.Value);

        //        //根据用户名
        //        Warehouse.BLL.BuyCart buyCartManager = new Warehouse.BLL.BuyCart();
        //        DataSet dsBuyCart = buyCartManager.GetList(string.Format("UserName='{0}'", userModel.UserName));



        //        //添加订单
        //        //将这里的优惠ID修改为真实的优惠金额(在业务逻辑里进行处理)
        //        if (dsBuyCart == null || dsBuyCart.Tables.Count == 0 || dsBuyCart.Tables[0].Rows.Count == 0)
        //        {
        //            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "mesdsada2323s", "alert('通吃卡ID为:" + tongchiCardId + "')", true);
        //            orderId = orderManager.Add(orderModel, itemList, productList, CartId, userModel.UserName, tongchiCardId, out msg);
        //        }
        //        else
        //        {
        //            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "mesd545sadas", "alert('通吃卡ID为:" + tongchiCardId + "')", true);
        //            orderId = orderManager.Add(orderModel, itemList, productList, CartId, userModel.UserName, tongchiCardId, out msg);
        //        }
        //        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "mes4755dsadas", "alert('通吃卡ID为:" + tongchiCardId + "')", true);
        //        if (orderId <= 0)
        //        {
        //            //Response.Write(msg);
        //            //Response.End();
        //            WebUnits.MessageBox(this, true, msg, "cart.aspx");
        //            return;
        //        }
        //        if (rbAddressList.SelectedItem.Value.Trim().Equals("-1") && ckBoxAddress.Checked)
        //        {
        //            mt.Model.MyAddress myAddressModel = new mt.Model.MyAddress();
        //            myAddressModel.userId = userId;
        //            myAddressModel.province = mt.WebUnits.DataOperater.ReplaceBadSQL(txtProvince.SelectedItem.Text.Trim());
        //            myAddressModel.city = mt.WebUnits.DataOperater.ReplaceBadSQL(dpCity.SelectedItem.Text.Trim());
        //            myAddressModel.district = mt.WebUnits.DataOperater.ReplaceBadSQL(dpDis.SelectedItem.Text.Trim());
        //            myAddressModel.detail = mt.WebUnits.DataOperater.ReplaceBadSQL(txtJiedao.Text.Trim());
        //            myAddressModel.contacterName = mt.WebUnits.DataOperater.ReplaceBadSQL(txtContacterName.Text.Trim());
        //            myAddressModel.phone = mt.WebUnits.DataOperater.ReplaceBadSQL(txtPhone.Text.Trim());
        //            myAddressModel.mobile = mt.WebUnits.DataOperater.ReplaceBadSQL(txtMobile.Text.Trim());
        //            myAddressModel.sender = mt.WebUnits.DataOperater.ReplaceBadSQL(txtSender.Text.Trim());
        //            myAddressModel.zipCode = mt.WebUnits.DataOperater.ReplaceBadSQL(txtSendPhone.Text.Trim());
        //            myAddressModel.createtime = DateTime.Now;
        //            myAddress.Add(myAddressModel);
        //        }
        //        if (msg.Trim().Length > 0)
        //        {
        //            WebUnits.MessageBox(this, false, msg, "");
        //        }
        //        mt.Model.Orders ordersModelnew = orderManager.GetModel(orderId);
        //        if (userModel.Islocked == 12 || userModel.Islocked == 2)
        //        {
        //            mt.BLL.Users userBll = new mt.BLL.Users();
        //            mt.Model.Users userModelNew = userBll.GetModel(userModel.UserID);
        //            ordersModelnew.Beiyong9 = "网址:" + userModelNew.Answer + "<br/>" + userModelNew.Question;
        //        }
        //        else
        //        {
        //            ordersModelnew.Beiyong9 = "网址:<br/>感谢你的惠顾,通吃网—打造中国最大的一站式食品采购平台";
        //        }
        //        orderManager.Update(ordersModelnew);

        //        //判断是否为预存款支付
        //        if (orderModel.PaymentType == 1)
        //        {
        //            //预存款支付
        //            orderId = orderManager.UpdateMy(orderInfo.OrderNum, out msg);
        //            if (orderId != 1)
        //            {
        //                WebUnits.MessageBox(this, true, msg, "cart.aspx");
        //                return;
        //            }
        //        }
        //        Session["temOrderNum"] = orderId.ToString();
        //        //重新将订单重置为null
        //        addLogDoucument("我的支付信息", string.Format("提交订单成功,订单编号:{0}", orderModel.OrderNum));
        //        orderInfo = null;
        //        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "hjo", "alert('错了')", true);
        //        //addYouhui();//首次下单送5元优惠卷
        //        Response.Redirect("MyOrder.aspx?orderNum=" + orderId, false);

        //    }
        //    catch (Exception ex)
        //    {
        //        Response.Write(ex.StackTrace);
        //        Response.End();
        //        addErrorLogDocument(ex, "我的支付信息错误", "提交订单失败");
        //        mt.WebUnits.WebUnits.MessageBox(this, false, "由于你在本页面停留时间过长,\\n请返回购物车重新进入收银台,谢谢!\\n如有问题请咨询客服。", "");
        //    }
        //}

        /// <summary>
        /// 验证订单是否成功下订,并输出结果给支付宝
        /// </summary>
        void WriteMemeryString() 
        {
            QREnty enty = this.GetQREntyByParamerts();                             //得到二维码实体信息
            QRProductOrders tmpModel = this.CreateQROrdersByParamerters(enty);         //得到二维码订单实体
            this.WrtieLogSign("tmpModeltmpModeltmpModel",tmpModel.OrderNum);
      
            mt.Model.Orders order = setOrder(tmpModel);                            //得到平台订单信息
            tmpModel.OrderNum = order.OrderNum;
            this.WrtieLogSign("orderorderorderorderorder", order.OrderNum);

            bool validateAllCreateOrder = this.ValidateCreateOrder(enty, tmpModel,order);//是否所有订单成功执行
            this.WrtieLogSign("Boolokokokkokok", validateAllCreateOrder.ToString());
           
            //JsonObjectByAlipay obj = this.WrtieAlipayObj(order,validateAllCreateOrder); //创建json输出对象
            //////把目标对象序列化为Json字符串
            //string tmpStr = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            //this.WrtieLogSign("resposeBuffer", tmpStr);
            string tmpStr = null;
            if(validateAllCreateOrder)
            {
                tmpStr = "{result:1,outTradeNo:" + order.OrderNum + ",memo:成功}";
            }else
            {
                tmpStr = "{result:-1,memo:失败}";
            }
            File.WriteAllText(Server.MapPath("~") + "ResultRepose.txt", tmpStr, System.Text.Encoding.UTF8);
            Response.Write(tmpStr);
            Response.Flush();
        }

         //{result:1,outTradeNo:1234567890,money:56.50,memo:成功}
        //{result:-1,memo:失败}

        /// <summary>
        /// 返回数据类
        /// </summary>
        [Serializable]
        public class JsonObjectByAlipay 
        {
            bool result;
            /// <summary>
            /// 是否成功
            /// </summary>
            public bool Result
            {
                get { return result; }
                set { result = value; }
            }

            string outTradeNo;
            /// <summary>
            /// 订单号
            /// </summary>
            public string OutTradeNo
            {
                get { return outTradeNo; }
                set { outTradeNo = value; }
            }

        }

        /// <summary>
        /// 拼接输出给支付宝的订单信息
        /// </summary>
        /// <returns>string</returns>
        JsonObjectByAlipay WrtieAlipayObj(mt.Model.Orders orders, bool bol) 
        {
            if(orders != null)
            {
                JsonObjectByAlipay obj = new JsonObjectByAlipay();
                obj.OutTradeNo = orders.OrderNum;
                obj.Result = bol;
                return obj;
            }
            this.WrtieLogSign("WrtieAlipayObj","创建输出json对象失败.原因为order为null");
            return null;
        }

        string message = null;
        /// <summary>
        /// 验证订单创建是否全部成功
        /// </summary>
        /// <returns>bool</returns>
        bool ValidateCreateOrder(QREnty enty, QRProductOrders tmpModel,mt.Model.Orders order) 
        {
            if (this.addQRProductOrders(tmpModel))
            {
                if (addOrders(enty, tmpModel,order,order.OrderID, out message))
                {
                    File.WriteAllText(Server.MapPath("~") + "Result.txt", message, System.Text.Encoding.UTF8);
                    return true;
                }
            }
            return false;
        }

        #region 创建自身平台订单Orders

        /// <summary>
        /// 创建二维码产品订单
        /// </summary>
        /// <returns>bool 为true为真否则为假</returns>
        QRProductOrders CreateQROrdersByParamerters(QREnty qr) 
        {
            if(dic != null)
            {
                if(dic.Count > 0)
                {
                    if(qr != null)
                    {
                        QRProductOrders enty = new QRProductOrders();
                        enty.QRCodeID = qr.QRID;
                        enty.OrderNum = DateTime.Now.ToString("yyyyMMddhhmmss") + Convert.ToString(new Random().Next(100001, 999999));
                        enty.BuyerName = dic["buyerName"];
                        enty.BuyerPhone = dic["phone"];
                        enty.BuyerAddress = dic["address"];
                        enty.BuyerPostCode = dic["postCode"];
                        enty.ProductCount = dic["count"] != null ? Convert.ToInt32(dic["count"]) : 0;
                        enty.Alipaytradeno = "";
                        enty.Money = dic["price"] != null ? Convert.ToDecimal(dic["price"]) : 0;
                        enty.Result = false;
                        return enty;
                    }
                    this.WrtieLogSign("GetQRCodISNull", "二维码产品实体为空。返回参数二维码在数据库中不存在");
                    this.WrtieLogSign("ParamertsISNull", "参数为空或没有参数");
                }
                
            }
            this.WrtieLogSign("ParamertsISNull", "参数为空或没有参数");
            this.WrtieLogSign("CreateQRCodeOrderErro", "创建自身平台订单:创建二维码订单失败或错误。请查阅代码276行");
            return null;
        }

        /// <summary>
        /// 新增二维码产品订单
        /// </summary>
        /// <param name="productOrder">二维码产品订单实体</param>
        /// <returns></returns>
        bool addQRProductOrders(QRProductOrders productOrder)
        {
            QRProductOrdersDAL dal = new QRProductOrdersDAL();
            if (dal.Add(productOrder) > 0)
            {
                return true;
            }
            this.WrtieLogSign("CreateQRCodeOrderErro", "创建自身平台订单:创建二维码订单失败或错误。请查阅代码285行");
            return false;
        }

        /// <summary>
        /// 创建自身平台订单Orders
        /// </summary>
        /// <param name="enty">二维码实体</param>
        /// <param name="productOrders">二维码订单实体</param>
        /// <param name="mssg">信息输出</param>
        /// <returns>bool 为真执行成功否则失败</returns>
        bool addOrders(QREnty enty, QRProductOrders productOrders, mt.Model.Orders tmpOrders,int tmpOrderID, out string mssg) 
        {
            //mt.Model.Orders tmpOrders = this.setOrder(productOrders);          
            if (tmpOrders.OrderID > 1) //如果插入订单基本信息成功
            {
                //tmpOrders = new mt.BLL.Orders().GetModel(tmpOrderID);
                this.WrtieLogSign("setOrderItems", "setOrderItems");
                List<mt.Model.OrderItems> tmpListOrderItems = this.setOrderItems(enty,tmpOrders,productOrders);
                this.WrtieLogSign("setOrderItemsRighte", "setOrderItemsRighte");
                this.WrtieLogSign("setProductList", "setProductList");
                List<mt.Model.Products> listProduct = this.setProductList(enty);
                this.WrtieLogSign("setProductListRighte", "setProductListRighte");
                this.WrtieLogSign("CreateOrderOrderMangeByID", "创建自身平台订单:成功");
                mssg = "成功";
                File.WriteAllText(Server.MapPath("~") + "CreateOrderErro.txt", message, System.Text.Encoding.UTF8);
                return true;
            }
            mssg = "OrderID value is 1 or 0";
            File.WriteAllText(Server.MapPath("~") + "CreateOrderErro.txt", message, System.Text.Encoding.UTF8);
            this.WrtieLogSign("CreateOrderErro", "创建自身平台订单:创建订单失败或错误。请查阅代码303行");
            return false;
        }

        /// <summary>
        /// 通过产品名获得产品信息
        /// </summary>
        /// <returns>mt.Model.Products实体</returns>
        mt.Model.Products GetProduct(mt.Model.Products product)
        {
            if (product != null)
            {
                if (product.ProductID > 0)
                {
                    product = new mt.BLL.Products().GetModel(product.ProductID);
                    return product;
                }
            }
            this.WrtieLogSign("GetModelProductByNameErro", "根据产品名获得产品信息失败或错误,请查阅代码296行");
            return null;
        }

        /// <summary>
        /// 创建订单信息
        /// </summary>
        /// <param name="enty">二维码产品实体</param>
        /// <param name="qroders">二维码订单实体(相关form表单参数)</param>
        /// <returns>二维码订单实体</returns>
        mt.Model.Orders setOrder(QRProductOrders qroders)
        {
            #region 订单数据
            mt.Model.Orders orderModel = new mt.Model.Orders();
            mt.Model.Users myUserModel = new mt.BLL.Users().GetModel("huangxiangcs");
            orderModel.OrderNum = qroders.OrderNum;
            orderModel.UserName = myUserModel != null ? myUserModel.UserName : "ZFB2088502788475631";
            orderModel.ClientId = myUserModel != null ? myUserModel.UserID :  113330;
            //继续创建订单属性
            orderModel.MoneyGoods = qroders.Money;//商品总价格
            orderModel.MoneyTotal = qroders.Money;//商品总价格
            orderModel.NeedInvoice = 0;
            orderModel.Invoiced = 1;
            orderModel.Remark = "二维码订单";
            orderModel.InputTime = DateTime.Now;
            orderModel.ContacterName = qroders.BuyerName;//收货人
            orderModel.Address = qroders.BuyerAddress;//地址
            orderModel.ZipCode = qroders.BuyerPostCode;//邮编
            orderModel.Mobile = qroders.BuyerPhone;
            orderModel.Phone = qroders.BuyerPhone;
            orderModel.Email = qroders.BuyerPhone;//发货人
            orderModel.PaymentType = 0;//int.Parse(rbPayType.SelectedValue);//支付方式
            orderModel.DeliverType = 6;//送货方式   //邮政快递
            orderModel.Status = 2;
            orderModel.PresentExp = 0;
            orderModel.ChargeDeliver = 0;
            orderModel.invoiceContent = "";
            orderModel.DeliverStatus = 1;
            orderModel.MoneyReceipt = 0;
            orderModel.YouHuiId = 0;
            orderModel.KuaiDiType = "邮政快递";
            orderModel.Beiyong1 = "";
            orderModel.Beiyong2 = ""; 
            orderModel.Beiyong3 = ""; 
            orderModel.Beiyong4 = ""; 
            orderModel.Beiyong5 = ""; 
            orderModel.Beiyong6 = ""; 
            orderModel.Beiyong7 = "";
            orderModel.Beiyong8 = "";
            orderModel.Beiyong9 = "";
            orderModel.Beiyong10 = "";
            mt.BLL.Orders orderMange = new mt.BLL.Orders();
            //add Order
            int tmpOrderID = orderMange.Add(orderModel);
            //GET ORDERID
            orderModel.OrderID = tmpOrderID;
            this.WrtieLogSign("orderid", orderModel.OrderID.ToString());
            return orderModel;
            #endregion
        }

        /// <summary>
        /// 创建订单详情集
        /// </summary>
        /// <param name="enty">QREnty 二维码实体信息</param>
        /// <param name="orders">Orders 二维码平台订单实体</param>
        /// <param name="productOrders">QRProductOrders 二维码订单详情</param>
        /// <returns>List《mt.Model.OrderItems》 订单详情集</returns>
        List<mt.Model.OrderItems> setOrderItems(QREnty enty,mt.Model.Orders orders,QRProductOrders productOrders) 
        {
            //获得对应产品信息
            mt.Model.Products pro = new mt.Model.Products();
            pro.ProductID = enty.ProductID;
            this.WrtieLogSign("setOrderItemsGetProduct", "setOrderItemsGetProduct");
            pro = this.GetProduct(pro);
            this.WrtieLogSign("setOrderItemsGetProductOK", "setOrderItemsGetProductOK");
            mt.Model.OrderItems orderItems = new mt.Model.OrderItems();
            orderItems.OrderID = orders.OrderID;
            orderItems.ProductID = pro.ProductID;
            orderItems.SaleType = 1;
            orderItems.PriceOriginal = pro.ProductType == 4 ? pro.PriceOriginal : pro.Price;
            orderItems.TruePrice = pro.ProductType == 4 ? pro.PriceOriginal : pro.Price;
            orderItems.Amount = productOrders.ProductCount;
            orderItems.SubTotal = productOrders.Money;
            orderItems.BeginDate = DateTime.Now;
            orderItems.Remark = "二维码商品,该产品不能享受代理";
            orderItems.PresentExp = 0;
            orderItems.price = pro.ProductType == 4 ? pro.PriceOriginal : pro.Price;
            orderItems.itemType = 1;
            orderItems.itemText = "二维码商品,该产品不能享受代理";
            orderItems.itembeiyong1 = 1;
            orderItems.itembeiyong2 = 0;
            orderItems.itembeiyong3 = "";
            orderItems.itembeiyong4 = "";
            mt.BLL.OrderItems itemsMange = new mt.BLL.OrderItems();
            List<mt.Model.OrderItems> itemlist = new List<mt.Model.OrderItems>();
            if(itemsMange.Add(orderItems) > 1)
            {
                this.WrtieLogSign("Cre0torderaRight", "创建自身平台订单:chenggong");
                itemlist.Add(orderItems);
                return itemlist;
            }
            File.WriteAllText(Server.MapPath("~") + "CreateOrdersItemsListErro.txt", "创建自身平台订单:创建订单详情集失败或错误", System.Text.Encoding.UTF8);
            this.WrtieLogSign("CreateOrdersItemsListErro", "创建自身平台订单:创建订单详情集失败或错误。请查阅代码358行");
            return null;
        }

        /// <summary>
        /// 创建产品集
        /// </summary>
        /// <param name="enty">二维码产品实体</param>
        /// <returns>List《mt.Model.Products》 产品详情集</returns>
        List<mt.Model.Products> setProductList(QREnty enty) 
        {
            List<mt.Model.Products> listProduct = new List<mt.Model.Products>();
            mt.Model.Products pro = new mt.Model.Products();
            pro.ProductID = enty.ProductID;
            pro = this.GetProduct(pro);
            if (pro != null)
            {
                listProduct.Add(pro);
                return listProduct;
            }
            this.WrtieLogSign("CreateListProdutcErro","创建自身平台订单:创建商品集失败或错误。请查阅代码398行");
            return null;
        }

        #endregion

        /// <summary>
        /// 通过post提交表单参数信息获得二维码实体信息
        /// </summary>
        /// <returns></returns>
        QREnty GetQREntyByParamerts() 
        {
            if(dic != null)
            {
                if(dic.Count > 0)
                {
                    QREnty enty = new QREnty();
                    enty.QRCode = dic["qrcode"] != null ? dic["qrcode"].ToString() : "";
                    enty = new QREntyDAL().GetModel(enty, 1);
                    this.WrtieLogSign("GetQRCodeRight", "正确返回二维码产品实体");
                    return enty;
                }
            }
            this.WrtieLogSign("GetQRCodeErro", "通过参数活动二维码实体失败");
            return null;
        }

        #region sign 操作

        /// <summary>
        /// 验证是否是支付宝发来的请求
        /// </summary>
        /// <returns>true验证成功</returns>
        bool ValidateSign() 
        {
            if(dic != null)
            {
                if (dic["sign"] != null)
                {
                    if (dic["sign"].ToString().ToLower().Equals(this.GetMySign(dic).ToLower()))
                    {
                        return true;
                    }
                    File.WriteAllText(Server.MapPath("~") + "SignUnlikeness.txt", "signVlidateErro", System.Text.Encoding.UTF8);
                    this.WrtieLogSign("SignUnlikeness", "Sign验证失败:1、请检查是否有人恶意攻击2、mysign生成方法存在问题_请检查相关源码:421行");
                    return false;
                }
                //else 
                //{
                //    File.WriteAllText(Server.MapPath("~") + "signNoErro.txt", "SignNoErro", System.Text.Encoding.UTF8);
                //    return false;
                //}
            }
            return false;
        }

        #region   获得签名证书
        /// <summary>
        /// 生成sign
        /// </summary>
        /// <param name="dicParameters">表单提交的参数集合</param>
        /// <returns>sign</returns>
        public string GetMySign(Dictionary<string,string> dicParameters)
        {
            String rootPath = Server.MapPath("~");//用于测试
            //File.WriteAllText(rootPath + "进入GetMySign.txt", "进入了方法", System.Text.Encoding.UTF8);
            List<string> Orstr = new List<string>();
            //File.WriteAllText(rootPath + "参数集合个数.txt", "参数个数:" + dicParameters.Count, System.Text.Encoding.UTF8);
            //this.WrtieLogSign("DeleteParamertsGetMySign", "删除生成sign参数失败。请查阅代码444行");
            #region sign生成
            Orstr.Add("qrcode=" + dicParameters["qrcode"]);
            File.WriteAllText(rootPath + "qrcode.txt", "qrcode:" + dicParameters["qrcode"], System.Text.Encoding.UTF8);
            Orstr.Add("price="+dicParameters["price"]);
            File.WriteAllText(rootPath + "price.txt", "price:" + dicParameters["price"], System.Text.Encoding.UTF8);
            Orstr.Add("count="+dicParameters["count"]);
            File.WriteAllText(rootPath + "count.txt", "count:" + dicParameters["count"], System.Text.Encoding.UTF8);
            Orstr.Add("subject="+dicParameters["subject"]);
            File.WriteAllText(rootPath + "subject.txt", "subject:" + dicParameters["subject"], System.Text.Encoding.UTF8);
            Orstr.Add("buyerName="+dicParameters["buyerName"]);
            File.WriteAllText(rootPath + "buyerName.txt", "buyerName:" + dicParameters["buyerName"], System.Text.Encoding.UTF8);
            Orstr.Add("phone="+dicParameters["phone"]);
            Orstr.Add("address=" + dicParameters["address"]);
            Orstr.Add("postCode="+dicParameters["postCode"]);
            //Orstr.Add(dic["qrcode"]);
            //File.WriteAllText(rootPath + "tempDicParamertsCount.txt", "count:" + Orstr.Count, System.Text.Encoding.UTF8);
            //进行排序;
            List<string> Sortedstr = BubbleSort(Orstr);
            //构造待md5摘要连接字符串
            System.Text.StringBuilder prestr = new System.Text.StringBuilder();
            for (int i = 0; i < Sortedstr.Count; i++)
            {
                if (i == Sortedstr.Count - 1)
                {
                    prestr.Append(Sortedstr[i]);
                }
                else
                {
                    prestr.Append(Sortedstr[i] + "&");
                }
            }
            //联测key
            //   自我开发测试key
            prestr.Append("&key=");
            String rootsPath = Server.MapPath("~");//用于测试

            //string tmpTest = "address=中南海&buyerName=北京中南海&count=2&phone=18668098188&postCode=100000&price=28.50&qrcode=[Alipay]:7648084772057216&subject=易网合纵&key=adsljiwfjk28fj28skskksf";
            File.WriteAllText(rootsPath + "Parameters" + "signString.txt", prestr.ToString(), System.Text.Encoding.UTF8);
            //生成Md5摘要;
            string sign = GetMD5(prestr.ToString(), "UTF-8");
           
            File.WriteAllText(rootsPath + sign + "sign.txt", sign, System.Text.Encoding.UTF8);
            //以下是POST方式传递参数
            return sign;
            #endregion
            //}
            
            return null;
        }

        /// <summary>
        /// 冒泡排序法
        /// </summary>
        public static List<string> BubbleSort(List<string> r)
        {
            int i, j; //交换标志 
            string temp;

            bool exchange;

            for (i = 0; i < r.Count; i++) //最多做R.Length-1趟排序 
            {
                exchange = false; //本趟排序开始前,交换标志应为假

                for (j = r.Count - 2; j >= i; j--)
                {//交换条件
                    if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0)
                    {
                        temp = r[j + 1];
                        r[j + 1] = r[j];
                        r[j] = temp;
                        exchange = true; //发生了交换,故将交换标志置为真 
                    }
                }

                if (!exchange) //本趟排序未发生交换,提前终止算法 
                {
                    break;
                }
            }
            return r;
        }


        /// <summary>
        /// 与ASP兼容的MD5加密算法
        /// </summary>
        public static string GetMD5(string s, string _input_charset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding(_input_charset).GetBytes(s));
            System.Text.StringBuilder sb = new System.Text.StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }

        #endregion

        #region  支付宝信息获得
        /// <summary>
        /// 获取支付宝POST过来通知消息
        /// </summary>
        /// <returns>Dictionary:参数key参数value键值对</returns>
        public Dictionary<string, string> GetRequestPost(Dictionary<string, string> sArray)
        {
            // Get names of all forms into a string array.
            if (Request.Form != null)
            {
                if (Request.Form.Count > 0)
                {
                    //String rootPath = Server.MapPath("~");
                    //File.WriteAllText(rootPath + "trueGetRequestPost.txt", "requestItem true");
                    for (int i = 0; i < Request.Form.Count; i++)
                    {
                        sArray.Add(Request.Form.GetKey(i), Request.Form.Get(i));
                        ////进行测试
                        WrtieLogSign(Request.Form.GetKey(i), Request.Form.Get(i));
                    }
                }
            }
            return sArray;
        }
        #endregion

        #endregion

        /// <summary>
        /// 日志生成
        /// </summary>
        /// <param name="txtName">日志生成文件名</param>
        /// <param name="content">日志生成内容</param>
        public void WrtieLogSign(string txtName, string content)
        {
            String rootPath = Server.MapPath("/ReturnLog/");
            string tmpTime = DateTime.Now.ToString().Replace(":", "").Replace("-", "").Replace("_", "").Replace("/", "");
            File.WriteAllText(rootPath + tmpTime + txtName + ".txt", tmpTime + ":" + content, System.Text.Encoding.UTF8);
        }

        //        using Newtonsoft.Json;
        //using Newtonsoft.Json.Converters;

        ////把Json字符串反序列化为对象
        //目标对象 = JavaScriptConvert.DeserializeObject(JSON字符串, typeof(目标对象));
        ////把目标对象序列化为Json字符串

        //string Json字符串 = JavaScriptConvert.SerializeObject(目标对象);

        //1.引用Newtonsoft.Json.dll
        //2.在项目中添加引用..
        //序列化和反序列在.net项目中:

        //Product product = new Product();

        //product.Name = "Apple";
        //product.Expiry = new DateTime(2008, 12, 28);
        //product.Price = 3.99M;
        //product.Sizes = new string[] { "Small", "Medium", "Large" };

        //string output = JavaScriptConvert.SerializeObject(product);
        ////{
        //// "Name": "Apple",
        //// "Expiry": new Date(1230422400000),
        //// "Price": 3.99,
        //// "Sizes": [
        ////      "Small",
        ////      "Medium",
        ////      "Large"
        //// ]
        ////}

        //Product deserializedProduct = (Product)JavaScriptConvert.DeserializeObject(output, typeof(Product));

        //读取JSON

        //string jsonText = "['JSON!',1,true,{property:'value'}]";

        //JsonReader reader = new JsonReader(new StringReader(jsonText));

        //Console.WriteLine("TokenType\t\tValueType\t\tValue");

        //while (reader.Read())
        //{
        //      Console.WriteLine(reader.TokenType + "\t\t" + WriteValue(reader.ValueType) + "\t\t" + WriteValue(reader.Value))
        //}

        //结果显示:
        //TokenType ValueType Value 
        //StartArray null null 
        //String System.String JSON! 
        //Integer System.Int32 1 
        //Boolean System.Boolean True 
        //StartObject null null 
        //PropertyName System.String property 
        //String System.String value 
        //EndObject null null 
        //EndArray null null

        //JSON写入
        //StringWriter sw = new StringWriter();
        //JsonWriter writer = new JsonWriter(sw);

        //writer.WriteStartArray();
        //writer.WriteValue("JSON!");
        //writer.WriteValue(1);
        //writer.WriteValue(true);
        //writer.WriteStartObject();
        //writer.WritePropertyName("property");
        //writer.WriteValue("value");
        //writer.WriteEndObject();
        //writer.WriteEndArray();

        //writer.Flush();

        //string jsonText = sw.GetStringBuilder().ToString();

        //Console.WriteLine(jsonText);
        //// ['JSON!',1,true,{property:'value'}]
    }
}


notify页面源码(页面部分是空的):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Net;
using mt.Model;
using mt.WebUnits;
using mt.DB;
using mt.DAL;
using mt.BLL;
using System.Collections;
using System.Data;
using System.Security.Cryptography;

namespace TopAPIDemo
{
    public partial class notify_url : System.Web.UI.Page
    {
        Dictionary<string, string> dic = null;
        /// <summary>
        /// sign验证参数是否被篡改验证方式(1.将出其自身之外的所有支付宝通知参数进行a-z排序后。2.加上支付宝给的KEY。3.进行MD5加密,如果计算出来的值与该值相等,说明参数未被篡改)
        /// </summary>
        string tmpSignByParmerts = null;
        /// <summary>
        /// 获得支付宝通知(通过二维码下单客户在我们平台自身的交易订单号)
        /// </summary>
        string tmpOuttradenonByParmerts = null;
        /// <summary>
        ///  获得支付宝通知(通过二维码下单客户在支付宝上的交易订单号)
        /// </summary>
        string tmpAlipaytradenoByParmerts = null;
        /// <summary>
        /// 获得支付宝通知(通过二维码下单客户支付的交易状态:成功或失败.T:支付成功.F:支付失败)
        /// </summary>
        string tmpResultByParmerts = null;
        /// <summary>
        /// 获得支付宝通知(通过二维码下单客户支付的金额)
        /// </summary>
        string tmpMoneyByParmerts = null;

        bool validateAllCreateOrder = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            //if(!IsPostBack)
            //{
            dic = new Dictionary<string, string>();
            dic = this.GetRequestPost(dic);
            validateAllCreateOrder = this.validateOrders(dic);
            Response.Write(ResposAlipay(validateAllCreateOrder));
        }

        string ResposAlipay(bool bol) 
        {
            string tmp = null;
            if(bol)
            {
                tmp = "{result:1}";
            }else
            {
                tmp = "{result:0}";
            }
            return tmp;
        }

        /// <summary>
        /// 返回数据类
        /// </summary>
        [Serializable]
        public class JsonObjectByAlipayNotify
        {
            bool result;
            /// <summary>
            /// 是否成功
            /// </summary>
            public bool Result
            {
                get { return result; }
                set { result = value; }
            }
        }

        /// <summary>
        /// 拼接输出给支付宝的订单信息
        /// </summary>
        /// <returns>string</returns>
        JsonObjectByAlipayNotify WrtieAlipayNotifyObj(bool bol)
        {
            JsonObjectByAlipayNotify obj = new JsonObjectByAlipayNotify();
            obj.Result = bol;
            return obj;
        }

        /// <summary>
        /// 判断所有操作是否成功
        /// </summary>
        /// <param name="dic">返回参数集</param>
        /// <returns>bool</returns>
        bool validateOrders(Dictionary<string, string> dic) 
        {
            if (dic.Count > 0)
            {
                if (this.ValidteSign())
                {
                    QRProductOrders tmpenty = new QRProductOrders(); //查询对象
                    tmpenty.OrderNum = dic["outtradeno"];
                    tmpenty = new QRProductOrdersDAL().GetModel(tmpenty, 3);
                    tmpenty.Money = dic["money"] != null ? Convert.ToDecimal(dic["money"]) : 0;
                    tmpenty.Result = dic["result"] == "T" ? true : false;
                    tmpenty.Alipaytradeno = dic["alipaytradeno"];
                    bool tmpQRCodeOrders = this.updateOrders(tmpenty, 1);
                    bool tmpOrders = this.updateOrders(tmpenty, 2);
                    if (tmpQRCodeOrders)
                    {
                        if (tmpOrders)
                        {
                            return true;
                        }
                        else
                        {
                            this.WrtieLogSign("UpdateOrderErro", "修改订单失败");
                            return false;
                        }
                    }
                    else 
                    {
                        this.WrtieLogSign("UpdateQRCodeOrderErro", "修改二维码订单失败");
                        return false;
                    }
                }
            }
            this.WrtieLogSign("NoParamerts", "没能获取到GET通知参数");
            return false;

        }

        /// <summary>
        /// 修改订单
        /// </summary>
        /// <param name="tmpenty">二维码订单实体</param>
        /// <param name="order">平台订单实体</param>
        /// <param name="orderType">操作类型</param>
        /// <returns></returns>
        bool updateOrders(QRProductOrders tmpenty,int orderType) 
        {
            if(orderType == 1)//修改二维码产品订单
            {
                return new QRProductOrdersDAL().Update(tmpenty);
            }
            else if (orderType == 2)
            {
                //根据回传的平台订单号获得订单实体信息
                mt.Model.Orders order = new mt.BLL.Orders().GetModel(tmpenty.OrderNum);
                //修改订单状态
                order.Status = 3;
                //修改订单支付金额
                order.MoneyReceipt = tmpenty.Money;
                return new mt.BLL.Orders().Update(order) > 0 ? true : false; //开始进行订单修改
                
            }
            this.WrtieLogSign("UpdateOrdersErro","修改订单失败");
            return false;
        }  

        /// <summary>
        /// 开始对验证参数进行验证
        /// </summary>
        /// <returns></returns>
        bool ValidteSign() 
        {
            tmpSignByParmerts = dic["sign"];
            this.WrtieLogSign("sign", dic["sign"]);
            tmpOuttradenonByParmerts = dic["outtradeno"];
            this.WrtieLogSign("outtradeno", dic["outtradeno"]);
            tmpAlipaytradenoByParmerts = dic["alipaytradeno"];
            this.WrtieLogSign("alipaytradeno", dic["alipaytradeno"]);
            tmpResultByParmerts = dic["result"];
            this.WrtieLogSign("result", dic["result"]);
            tmpMoneyByParmerts = dic["money"];
            this.WrtieLogSign("money", dic["money"]);
            if (tmpSignByParmerts != null && tmpOuttradenonByParmerts != null && tmpAlipaytradenoByParmerts != null && tmpResultByParmerts != null && tmpMoneyByParmerts != null)
            {
                if (tmpSignByParmerts.Equals
                    (this.GetMySign(tmpOuttradenonByParmerts, tmpAlipaytradenoByParmerts, tmpResultByParmerts, Convert.ToDecimal(tmpMoneyByParmerts))))
                {
                    return true;
                }
                return false;
            }
            else
            {
                this.WrtieLogSign("NothingParamerters", "有参数为空。不能对Sign进行验证");
                return false;
            }
        }

        #region   生成签名证书

        /// <summary>
        /// 通过相关参数生成sign
        /// </summary>
        /// <param name="outtradeno">自身平台商户网站唯一订单号</param>
        /// <param name="alipaytradeno">支付宝唯一订单号</param>
        /// <param name="result">支付结果</param>
        /// <param name="money">支付金额</param>
        /// <returns></returns>
        public string GetMySign(string outtradeno, string alipaytradeno, string result, decimal money)
        {
            int i;
            string[] Oristr ={ 
                "outtradeno="+ outtradeno, 
                "alipaytradeno="+ alipaytradeno, 
                "result="+ result, 
                "money="+ money, 
                };
            //进行排序;
            //string[] Sortedstr = BubbleSort(Oristr);
            //构造待md5摘要字符串 ;
            System.Text.StringBuilder prestr = new System.Text.StringBuilder();
            for (i = 0; i < Oristr.Length; i++)
            {
                if (i == Oristr.Length - 1)
                {
                    prestr.Append(Oristr[i]);
                }
                else
                {
                    prestr.Append(Oristr[i] + "&");
                }
            }
            //联测key
            //自我开发测试key
            prestr.Append("&key=");
            //生成Md5摘要;
            //string tmpStr = "outtradeno=1111111&alipaytradeno=12312312&result=1&money=26.5&key=adsljiwfjk28fj28skskksf";
            //string tmpsign = GetMD5(tmpStr,"utf-8");
            //up test sign
            string sign = GetMD5(prestr.ToString(), "UTF-8");
            //String rootPath = Server.MapPath("~");测试
            this.WrtieLogSign("sign", sign);
            //File.WriteAllText(rootPath + "sign.txt", "sign", System.Text.Encoding.UTF8);
            return sign;
        }

        /// <summary>
        /// 冒泡排序算法
        /// </summary>
        /// <param name="r">排序过后的参数数组</param>
        /// <returns></returns>
        public static string[] BubbleSort(string[] r)
        {
            int i, j; //交换标志 
            string temp;
            bool exchange;
            for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序 
            {
                exchange = false; //本趟排序开始前,交换标志应为假

                for (j = r.Length - 2; j >= i; j--)
                {//交换条件
                    if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0)
                    {
                        temp = r[j + 1];
                        r[j + 1] = r[j];
                        r[j] = temp;
                        exchange = true; //发生了交换,故将交换标志置为真 
                    }
                }
                if (!exchange) //本趟排序未发生交换,提前终止算法 
                {
                    break;
                }
            }
            return r;
        }

        /// <summary>
        /// <summary>
        /// 与ASP兼容的MD5加密算法
        /// <param name="s">需要加密的字符串</param>
        /// <param name="_input_charset">按照什么编码格式进行加密</param>
        /// <returns></returns>
        public static string GetMD5(string s, string _input_charset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding(_input_charset).GetBytes(s));
            System.Text.StringBuilder sb = new System.Text.StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }

        #endregion

        /// <summary>
        /// 获取支付宝POST过来通知消息,并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        public Dictionary<string, string> GetRequestPost(Dictionary<string, string> sArray)
        {      
            if (Request.QueryString != null)
            {
                if (Request.QueryString.Count > 0)
                {
                    //String rootPath = Server.MapPath("~");
                    //File.WriteAllText(rootPath + "notifyrequestItem.txt", "notifyrequestItem true");
                    for (int i = 0; i < Request.QueryString.Count; i++)
                    {
                        sArray.Add(Request.QueryString.GetKey(i), Request.QueryString.Get(i));
                        //this.WrtieLogSign(Request.QueryString.GetKey(i), Request.QueryString.Get(i));
                    }
                }
            }
            return sArray;
        }


        /// <summary>
        /// 日志生成
        /// </summary>
        /// <param name="txtName">日志生成文件名</param>
        /// <param name="content">日志生成内容</param>
        void WrtieLogSign(string txtName, string content)
        {
            String rootPath = Server.MapPath("/NotifyLog/");
            string tmpTime = DateTime.Now.ToString().Replace(":", "").Replace("-", "").Replace("_", "").Replace("/", "");
            File.WriteAllText(rootPath + tmpTime + txtName + ".txt", tmpTime + ":" + content, System.Text.Encoding.UTF8);
        }

        //outtradeno	商户网站唯一订单号	String	商户网站唯一订单号,在商户系统内唯一。	不可空	20192808442644
        //alipaytradeno	支付宝交易号	String	支付宝交易号。	不可空	201111301367987
        //result	支付结果	String	T:支付成功
        //F:支付失败	不可空	T
        //method	动作	String	此处固定为paynotify。	不可空	paynotify
        //sign	签名	String	请参见“8  签名机制”。
        //本接口只支持MD5方式。	不可空	ex3ahchn9hhwnjtdkn7j96q5acpcoasb
    }
}

实体部分和数据访问部分信息(根据你自己的业务情况编写).这个是我的:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using mt.DAL.log;
using mt.DB;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Collections;
using System.Data.SqlClient;

namespace TopAPIDemo
{
    /// <summary>
    /// 二维码业务功能实体类
    /// </summary>
    public class QREnty
    {
        int qRID = 0;
        /// <summary>
        /// 二维码业务ID
        /// </summary>
        public int QRID
        {
            get { return qRID; }
            set { qRID = value; }
        }

        int productID = 0;
        /// <summary>
        /// 商品ID
        /// </summary>
        public int ProductID
        {
            get { return productID; }
            set { productID = value; }
        }

        string productName = null;
        /// <summary>
        /// 二维码商品名
        /// </summary>
        public string ProductName
        {
            get { return productName; }
            set { productName = value; }
        }
        string qRCode = null;
        /// <summary>
        /// 二维码
        /// </summary>
        public string QRCode
        {
            get { return qRCode; }
            set { qRCode = value; }
        }
        string imgUrl;
        /// <summary>
        /// 产品生成的二维码图片地址
        /// </summary>
        public string ImgUrl
        {
            get { return imgUrl; }
            set { imgUrl = value; }
        }

    }

    /// <summary>
    /// 二维码业务数据访问类
    /// </summary>
    public class QREntyDAL
    {

        /// <summary>
        /// 根据条件判断是否存在
        /// </summary>
        /// <param name="where">条件:需要条件.from后面包含where 的语句</param>
        /// <returns></returns>
        public bool Exists(string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from mt_QRCode ");
            strSql.Append(where);
            return DbHelperSQL.Exists(strSql.ToString());
        }

        /// <summary>
        /// <summary>
        /// 增加一条数据
        /// </summary>
        /// <param name="enty">二维码实体信息</param>
        /// <returns>二维码实体唯一标识id</returns>
        public int Add(QREnty enty)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into mt_QRCode(");
            strSql.Append("productID,productName,qRCode,imgurl)");
            strSql.Append(" values (");
            strSql.Append("@productID,@productName,@qRCode,@imgurl)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("productID", SqlDbType.Int,50),
					new SqlParameter("@productName", SqlDbType.NVarChar,2000),
					new SqlParameter("@qRCode", SqlDbType.NVarChar,2000),
					new SqlParameter("@imgurl", SqlDbType.NVarChar,2000)
				};
            parameters[0].Value = enty.ProductID;
            parameters[1].Value = enty.ProductName;
            parameters[2].Value = enty.QRCode;
            parameters[3].Value = enty.ImgUrl;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(QREnty enty)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update mt_QRCode set ");
            strSql.Append("productName=@productName,");
            strSql.Append("imgurl=@imgurl");
            strSql.Append(" where productName=@productName ");
            SqlParameter[] parameters = {
					new SqlParameter("@productName", SqlDbType.NVarChar,2000),
					new SqlParameter("@imgurl", SqlDbType.NVarChar,2000)};
            parameters[1].Value = enty.ProductName;
            parameters[2].Value = enty.ImgUrl;
            //记录执行结果
            int tmpCount = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            //如果修改成功返回true否则返回false
            return tmpCount > 0 ? true : false;
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(string entyQRCode)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from mt_QRCode ");
            strSql.Append(" where qRCode=@qRCode ");
            SqlParameter[] parameters = {
					new SqlParameter("@qRCode", SqlDbType.NVarChar,2000)};
            parameters[0].Value = entyQRCode;
            //记录执行结果
            int tmpCount = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            //执行成功为真否则为假
            return tmpCount > 0 ? true : false;
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int entyID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from mt_QRCode ");
            strSql.Append(" where QRID=@QRID ");
            SqlParameter[] parameters = {
					new SqlParameter("@QRID", SqlDbType.Int,32)};
            parameters[0].Value = entyID;
            //记录执行结果
            int tmpCount = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            //执行成功为真否则为假
            return tmpCount > 0 ? true : false;
        }

        /// <summary>
        /// 得到一个二维码对象实体
        /// </summary>
        /// <param name="enty">二维码对象实体查询条件值</param>
        /// <param name="SearType">检索类型。0:标识1:产品ID。2:产品名模糊查询3:平台单号。4:支付宝订单号。其他:是否成功。</param>
        /// <returns></returns>
        public QREnty GetModel(QREnty enty, int SearType)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select QRID,productID,productName,qRCode,imgurl from mt_QRCode ");
            #region 条件筛选并查询

            if (enty.QRID > 0 && SearType == 0)
            {
                strSql.Append(" where QRID=@QRID ");
                SqlParameter[] parameters = {
					new SqlParameter("@QRID", SqlDbType.Int,32)};
                parameters[0].Value = enty.QRID;
                return this.ReadEntyByDataSouse(strSql.ToString(), parameters);
            }
            else if (enty.QRCode != null && SearType == 1)
            {
                strSql.Append(" where qRCode=@qRCode ");
                SqlParameter[] parameters = {
					new SqlParameter("@qRCode", SqlDbType.NVarChar,2000)};
                parameters[0].Value = enty.QRCode;
                return this.ReadEntyByDataSouse(strSql.ToString(), parameters);
            }
            else if (enty.ProductName != null && SearType == 2)
            {
                strSql.Append(" where productName like '%" + enty.ProductName + "%'");
                return this.ReadEntyByDataSouse(strSql.ToString(),null);
            }
            return null;
            #endregion
        }

        /// <summary>
        /// 开始进行数据读取
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <param name="parameters">参数列表</param>
        /// <returns></returns>
        QREnty ReadEntyByDataSouse(string strSql, SqlParameter[] parameters)
        {
            QREnty model = new QREnty();
            try
            {
                DataSet ds = null;
                if (parameters != null)
                {
                    ds = DbHelperSQL.Query(strSql.ToString(), parameters);
                }
                else 
                {
                    ds = DbHelperSQL.Query(strSql.ToString());
                }
              
                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["QRID"] != null)
                    {
                        model.QRID = Convert.ToInt32(ds.Tables[0].Rows[0]["QRID"]);
                    }
                    if (ds.Tables[0].Rows[0]["productID"] != null)
                    {
                        model.ProductID = Convert.ToInt32(ds.Tables[0].Rows[0]["productID"]);
                    }
                    model.ProductName = ds.Tables[0].Rows[0]["productName"] != null ? ds.Tables[0].Rows[0]["productName"].ToString() : null;
                    model.QRCode = ds.Tables[0].Rows[0]["qRCode"] != null ? ds.Tables[0].Rows[0]["qRCode"].ToString() : null;
                    model.ImgUrl = ds.Tables[0].Rows[0]["imgurl"] != null ? ds.Tables[0].Rows[0]["imgurl"].ToString() : null;

                    return model;
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        /// <param name="fileName">需要查询的字段列表。实例 "id,name,age"</param>
        /// <param name="strWhere">查询条件。实例:"id = 1 and name like '%sss%' order by age desc"</param>
        /// <returns></returns>
        public DataSet GetList(string fileName, string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  ");
            strSql.Append(fileName);
            strSql.Append(" FROM mt_QRCode ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperSQL.Query(strSql.ToString());
        }
    }
}

二维码订单业务实体和数据访问类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using mt.DAL.log;
using mt.DB;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Collections;
using System.Data.SqlClient;

namespace TopAPIDemo
{
    /// <summary>
    /// 二维码业务功能实体类
    /// </summary>
    public class QRProductOrders
    {
        int qRID = 0;
        /// <summary>
        /// 二维码业务ID
        /// </summary>
        public int QRID
        {
            get { return qRID; }
            set { qRID = value; }
        }

        int qRCodeID = 0;
        /// <summary>
        /// 二维码产品商品ID
        /// </summary>
        public int QRCodeID
        {
            get { return qRCodeID; }
            set { qRCodeID = value; }
        }

        string orderNum = null;
        /// <summary>
        /// 自身平台订单号
        /// </summary>
        public string OrderNum
        {
            get { return orderNum; }
            set { orderNum = value; }
        }
        string buyerName = null;
        /// <summary>
        /// 收货人姓名
        /// </summary>
        public string BuyerName
        {
            get { return buyerName; }
            set { buyerName = value; }
        }
        string buyerPhone = null;
        /// <summary>
        /// 收货人联系方式
        /// </summary>
        public string BuyerPhone
        {
            get { return buyerPhone; }
            set { buyerPhone = value; }
        }
        string buyerAddress = null;
        /// <summary>
        /// 收货人地址
        /// </summary>
        public string BuyerAddress
        {
            get { return buyerAddress; }
            set { buyerAddress = value; }
        }
        string buyerPostCode = null;
        /// <summary>
        /// 收货人邮编地址
        /// </summary>
        public string BuyerPostCode
        {
            get { return buyerPostCode; }
            set { buyerPostCode = value; }
        }
        int productCount = 0;
        /// <summary>
        /// 交易商品数量
        /// </summary>
        public int ProductCount
        {
            get { return productCount; }
            set { productCount = value; }
        }

        string alipaytradeno = null;
        /// <summary>
        /// 支付宝平台唯一订单号
        /// </summary>
        public string Alipaytradeno
        {
            get { return alipaytradeno; }
            set { alipaytradeno = value; }
        }
        decimal money = 0;
        /// <summary>
        /// 交易金额
        /// </summary>
        public decimal Money
        {
            get { return money; }
            set { money = value; }
        }
        bool result = false;
        /// <summary>
        /// 交易状态.T:支付成功F:支付失败
        /// </summary>
        public bool Result
        {
            get { return result; }
            set { result = value; }
        }
    }

    /// <summary>
    /// 二维码业务数据访问类
    /// </summary>
    public class QRProductOrdersDAL
    {

        /// <summary>
        /// 根据条件判断是否存在
        /// </summary>
        /// <param name="where">条件:需要条件.from后面包含where 的语句</param>
        /// <returns></returns>
        public bool Exists(string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from mt_QRCodeOrderLog ");
            strSql.Append(where);
            return DbHelperSQL.Exists(strSql.ToString());
        }

        /// <summary>
        /// <summary>
        /// 增加一条数据
        /// </summary>
        /// <param name="enty">二维码实体信息</param>
        /// <returns>二维码实体唯一标识id</returns>
        public int Add(QRProductOrders enty)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into mt_QRCodeOrderLog(");
            strSql.Append("QRCodeID,orderNum,buyerName,buyerPhone,buyerAddress,buyerPostCode,productCount,alipaytradeno,money,result)");
            strSql.Append(" values (");
            strSql.Append("@QRCodeID,@orderNum,@buyerName,@buyerPhone,@buyerAddress,@buyerPostCode,@productCount,@alipaytradeno,@money,@result)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@QRCodeID", SqlDbType.Int,50),
					new SqlParameter("@orderNum", SqlDbType.NVarChar,2000),
                    new SqlParameter("@buyerName", SqlDbType.NVarChar,2000),
                    new SqlParameter("@buyerPhone", SqlDbType.NVarChar,2000),
                    new SqlParameter("@buyerAddress", SqlDbType.NVarChar,2000),
                    new SqlParameter("@buyerPostCode", SqlDbType.NVarChar,2000),
					new SqlParameter("@productCount", SqlDbType.Int,2000),
					new SqlParameter("@alipaytradeno", SqlDbType.NVarChar,2000),
					new SqlParameter("@money", SqlDbType.Decimal,18),
					new SqlParameter("@result", SqlDbType.Bit,2),
				};
            parameters[0].Value = enty.QRCodeID;
            parameters[1].Value = enty.OrderNum;
            parameters[2].Value = enty.BuyerName;
            parameters[3].Value = enty.BuyerPhone;
            parameters[4].Value = enty.BuyerAddress;
            parameters[5].Value = enty.BuyerPostCode;
            parameters[6].Value = enty.ProductCount;
            parameters[7].Value = enty.Alipaytradeno;
            parameters[8].Value = enty.Money;
            parameters[9].Value = enty.Result;
         

            object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(QRProductOrders enty)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update mt_QRCodeOrderLog set ");
            strSql.Append("orderNum='" + enty.OrderNum +"',");
            strSql.Append("buyerName='" + enty.BuyerName + "',");
            strSql.Append("buyerPhone='" + enty.BuyerPhone + "',");
            strSql.Append("buyerAddress='" + enty.BuyerAddress + "',");
            strSql.Append("buyerPostCode='" + enty.BuyerPostCode + "',");
            strSql.Append("productCount='" + enty.ProductCount + "',");
            strSql.Append("alipaytradeno='" + enty.Alipaytradeno + "',");
            strSql.Append("money='" + enty.Money + "',");
            strSql.Append("result='" + enty.Result + "'  ");
            strSql.Append("where orderNum='" + enty.OrderNum + "'");
            //记录执行结果
            System.IO.File.WriteAllText(HttpContext.Current.Server.MapPath("/NotifyLog/") + "sql.txt", strSql.ToString());
            int tmpCount = DbHelperSQL.ExecuteSql(strSql.ToString());
            //如果修改成功返回true否则返回false
            return tmpCount > 0 ? true : false;
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from mt_QRCodeOrderLog ");
            strSql.Append(" " + where);
            //记录执行结果
            int tmpCount = DbHelperSQL.ExecuteSql(strSql.ToString());
            //执行成功为真否则为假
            return tmpCount > 0 ? true : false;
        }

        /// <summary>
        /// 得到一个二维码对象实体
        /// </summary>
        /// <param name="enty">二维码对象实体查询条件值</param>
        /// <param name="SearType">检索类型。0:标识1:产品ID。2:产品名模糊查询3:平台单号。4:支付宝订单号。其他:是否成功。</param>
        /// <returns></returns>
        public QRProductOrders GetModel(QRProductOrders enty, int SearType)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select QRID,QRCodeID,orderNum,buyerName,buyerPhone,buyerAddress,");
            strSql.Append(" buyerPostCode,productCount,alipaytradeno,money,result from mt_QRCodeOrderLog ");

            #region 条件筛选并查询

            if (enty.QRID > 0 && SearType == 0)
            {
                strSql.Append(" where QRID=@QRID ");
                SqlParameter[] parameters = {
					new SqlParameter("@QRID", SqlDbType.Int,32)};
                parameters[0].Value = enty.QRID;
                return this.ReadEntyByDataSouse(strSql.ToString(), parameters);
            }
            else if (enty.QRCodeID != 0 && SearType == 1)
            {
                strSql.Append(" where QRCodeID=@QRCodeID ");
                SqlParameter[] parameters = {
					new SqlParameter("@QRCodeID", SqlDbType.Int,32)};
                parameters[0].Value = enty.QRCodeID;
                return this.ReadEntyByDataSouse(strSql.ToString(), parameters);
            }
            else if (enty.OrderNum != null && SearType == 3)
            {
                strSql.Append(" where orderNum=@orderNum ");
                SqlParameter[] parameters = {
					new SqlParameter("@orderNum", SqlDbType.NVarChar,2000)};
                parameters[0].Value = enty.OrderNum;
                return this.ReadEntyByDataSouse(strSql.ToString(), parameters);
            }
            else if (enty.Alipaytradeno != null && SearType == 4)
            {
                strSql.Append(" where alipaytradeno=@alipaytradeno ");
                SqlParameter[] parameters = {
					new SqlParameter("@alipaytradeno", SqlDbType.NVarChar,2000)};
                parameters[0].Value = enty.Alipaytradeno;
                return this.ReadEntyByDataSouse(strSql.ToString(), parameters);
            }
            else if (SearType == 2)
            {
                strSql.Append(" where result = @result ");
                SqlParameter[] parameters = {
					new SqlParameter("@result", SqlDbType.Bit,2)};
                parameters[0].Value = enty.Result;
                return this.ReadEntyByDataSouse(strSql.ToString(), parameters);
            }
         
            #endregion

            return null;
        }

        /// <summary>
        /// 开始进行数据读取
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <param name="parameters">参数列表</param>
        /// <returns></returns>
        QRProductOrders ReadEntyByDataSouse(string strSql, SqlParameter[] parameters)
        {
            QRProductOrders model = new QRProductOrders();
            try
            {
                DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["QRID"] != null)
                    {
                        model.QRID = Convert.ToInt32(ds.Tables[0].Rows[0]["QRID"]);
                    }
                    if (ds.Tables[0].Rows[0]["QRCodeID"] != null)
                    {
                        model.QRCodeID = Convert.ToInt32(ds.Tables[0].Rows[0]["QRCodeID"]);
                    }             
                    model.OrderNum = ds.Tables[0].Rows[0]["orderNum"] != null ? ds.Tables[0].Rows[0]["orderNum"].ToString() : null;
                    model.BuyerName = ds.Tables[0].Rows[0]["buyerName"] != null ? ds.Tables[0].Rows[0]["buyerName"].ToString() : null;
                    model.BuyerPhone = ds.Tables[0].Rows[0]["buyerPhone"] != null ? ds.Tables[0].Rows[0]["buyerPhone"].ToString() : null;
                    model.BuyerAddress = ds.Tables[0].Rows[0]["buyerAddress"] != null ? ds.Tables[0].Rows[0]["buyerAddress"].ToString() : null;
                    model.BuyerPostCode = ds.Tables[0].Rows[0]["buyerPostCode"] != null ? ds.Tables[0].Rows[0]["buyerPostCode"].ToString() : null;
                    if (ds.Tables[0].Rows[0]["productCount"] != null)
                    {
                        model.ProductCount = Convert.ToInt32(ds.Tables[0].Rows[0]["productCount"]);
                    }
                    model.Alipaytradeno = ds.Tables[0].Rows[0]["alipaytradeno"].ToString();

                    if (ds.Tables[0].Rows[0]["money"] != null)
                    {
                        model.Money = Convert.ToDecimal(ds.Tables[0].Rows[0]["money"]);
                    }
                    if (ds.Tables[0].Rows[0]["result"] != null)
                    {
                        model.Result = Convert.ToBoolean(ds.Tables[0].Rows[0]["result"]);
                    }
                    return model;
                }
                return null;
            }
            catch (Exception)
            {
                throw;
            }
            return null;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        /// <param name="fileName">需要查询的字段列表。实例 "id,name,age"</param>
        /// <param name="strWhere">查询条件。实例:"id = 1 and name like '%sss%' order by age desc"</param>
        /// <returns></returns>
        public DataSet GetList(string fileName, string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  ");
            strSql.Append(fileName);
            strSql.Append(" FROM mt_QRCodeOrderLog ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperSQL.Query(strSql.ToString());
        }
    }
}

至此.所有编码工作完成。当然,还需要建对应的表。注意:该代码介意别直接使用。我加了很多的测试日志生成。还有,该代码很多地方可以封装,而我没有哈。呵呵呵。

如果直接拿来用,产生的后果本人不负责噢。








最新评论

௸2128 发表于 2022-5-3 19:32
html网页源代码怎么下载

轻源码让程序更轻更快

QingYuanMa.com

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表