<%@ Page Language="C#" StylesheetTheme="" EnableTheming="false" Inherits="PowerEasy.Foundation.Web.UI.BasePage" %>
<%@ Import Namespace="PowerEasy.Module.General.WebSite.PayOnline" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        //PowerEasy.Module.Shop.BusinessLogic.PayOnline.TestLog(false, Resources.DynamicPageResources.PayOnline_PayResultAlipayGuarantee_ZhiFuBao, "", "", "");

        int payPlatformId = 16;  //支付宝中介担保交易
        PowerEasy.Module.General.Model.Accessories.PayPlatformInfo payPlatform = PowerEasy.Module.General.BusinessLogic.Accessories.PayPlatform.GetPayPlatformById(payPlatformId);
        if (payPlatform.IsDisabled || payPlatform.MD5 == "3069" || string.IsNullOrEmpty(payPlatform.MD5))
        {
            Response.Write(Resources.DynamicPageResources.PayOnline_PayResult99bill_ToPayNo);
            return;
        }
        string payOnlineShopID = payPlatform.AccountsId;
        string PayOnlineKey = payPlatform.MD5;

        string partner = "", key = "";

        if (PayOnlineKey.IndexOf("|") > 0)
        {
            string[] ArrMD5Key = payPlatform.MD5.Split('|');
            key = ArrMD5Key[0];        //partner 的对应交易安全校验码（必须填写）
            partner = ArrMD5Key[1];   //partner合作伙伴id（必须填写）
        }


        string v_oid = DelStr(Request["out_trade_no"]);           //商户订单号
        string trade_status = DelStr(Request["trade_status"]);
        string v_amount = DelStr(Request["price"]);
        string notify_id = Request.Form["notify_id"];

        string alipayNotifyURL = "https://mapi.alipay.com/gateway.do?service=notify_verify";

        alipayNotifyURL = alipayNotifyURL + "&partner=" + partner + "&notify_id=" + Request.Form["notify_id"];

        //获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的
        string responseTxt = Get_Http(alipayNotifyURL, 120000);

        int i;
        NameValueCollection coll;

        coll = Request.Form;

        String[] requestarr = coll.AllKeys;

        //进行排序；
        string[] Sortedstr = AliPay.BubbleSort(requestarr);

        //构造待md5摘要字符串 ；
        string prestr = "";
        for (i = 0; i < Sortedstr.Length; i++)
        {
            if (Request.Form[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr = prestr + Sortedstr[i] + "=" + Request.Form[Sortedstr[i]];
                }
                else
                {
                    prestr = prestr + Sortedstr[i] + "=" + Request.Form[Sortedstr[i]] + "&";
                }
            }

        }
        prestr = prestr + key;

        string mysign = PowerEasy.Framework.Common.DataCrypto.MD5(prestr).ToLower();


        string sign = Request.Form["sign"];
        string returnTxt = "fail";


        if (sign == mysign && responseTxt == "true")
        {
            PowerEasy.Module.Shop.BusinessLogic.PayOnline payOnline = new PowerEasy.Module.Shop.BusinessLogic.PayOnline();
            returnTxt = "success";

            switch (trade_status)
            {
                case "WAIT_SELLER_SEND_GOODS":      //买家付款成功,等待卖家发货
                    payOnline.UpdateOrder(v_oid, PowerEasy.Framework.Common.DataConverter.ToDecimal(v_amount), "", 2, "", false, false);
                    PowerEasy.Module.General.BusinessLogic.Accessories.PaymentLog.UpdateTradeNum(v_oid, Request["trade_no"].ToString());
                    break;
                case "WAIT_BUYER_CONFIRM_GOODS":    //卖家已发货等待买家确认
                    payOnline.UpdateOrder(v_oid, PowerEasy.Framework.Common.DataConverter.ToDecimal(v_amount), "", 4, "", true, false);
                    break;
                case "TRADE_FINISHED":              //交易成功结束
                    payOnline.UpdateOrder(v_oid, PowerEasy.Framework.Common.DataConverter.ToDecimal(v_amount), "", 3, "", true, true);
                    //Order.Recieve(DataConverter.ToInt32(HdnOrderId.Value));
                    //OrderHistory.AddOrderHistory(ViewState["OrderNum"].ToString(), "客户签收", "");
                    break;
                case "WAIT_BUYER_PAY":              //等待买家付款
                default:
                    break;
            }
        }
        Response.Write(returnTxt);
        //PowerEasy.Module.Shop.BusinessLogic.PayOnline.TestLog(false, Resources.DynamicPageResources.PayOnline_PayResultAlipayInstant_ZhiFuBao, trade_status, sign, mysign);
    }

    private string DelStr(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            str = "";
        }
        str = str.Replace(";", "");
        str = str.Replace("'", "");
        str = str.Replace("&", "");
        str = str.Replace(" ", "");
        str = str.Replace("　", "");
        str = str.Replace("%20", "");
        str = str.Replace("--", "");
        str = str.Replace("==", "");
        str = str.Replace("<", "");
        str = str.Replace(">", "");
        str = str.Replace("%", "");

        return str;
    }

    public string Get_Http(String a_strUrl, int timeout)
    {
        string strResult;
        try
        {
            System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(a_strUrl);
            myReq.Timeout = timeout;
            System.Net.HttpWebResponse HttpWResp = (System.Net.HttpWebResponse)myReq.GetResponse();
            System.IO.Stream myStream = HttpWResp.GetResponseStream();
            System.IO.StreamReader sr = new System.IO.StreamReader(myStream, Encoding.Default);
            StringBuilder strBuilder = new StringBuilder();
            while (-1 != sr.Peek())
            {
                strBuilder.Append(sr.ReadLine());
            }

            strResult = strBuilder.ToString();
        }
        catch (Exception exp)
        {
            strResult = Resources.DynamicPageResources.PayOnline_PayResultAlipayInstant_Err + exp.Message;
        }

        return strResult;
    }
</script>

