久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

支付寶及時(shí)到帳接口使用詳解

 有你最好DOC 2015-11-21
這兩天寫支付寶接口,, 這個(gè)話題不新了, 因?yàn)楹芏嗳硕?做過了,, 在這里我說說我的看法吧,, 先說一下實(shí)現(xiàn)
其實(shí)支付寶公司已經(jīng)給我們做的很好了,, 只要少量的改動(dòng)就OK了,只是有的程序員不太明天他們的動(dòng)作流程而以,,我就以及時(shí)到帳為例子來說了,,呵呵
在這之前就大家先下載一下c#版的及時(shí)到帳代碼
先看一下程序的結(jié)構(gòu)吧



支付寶有一個(gè)類文件叫 AliPay 是一些加密算法之類的東西,包括構(gòu)造URL
要吧看一下這個(gè)類的全部?jī)?nèi)容
[C#] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Net;
using System;
/// <summary>
/// New Interface for AliPay
/// </summary>
namespace Gateway
{
    public class AliPay
    {
        /// <summary>
        /// 與ASP兼容的MD5加密算法
        /// </summary>
        public static string GetMD5(string s, string _input_charset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t.ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 冒泡排序法
        /// 按照字母序列從a到z的順序排列
        /// </summary>
        public static string[] BubbleSort(string[] r)
        {
            int i, j; //交換標(biāo)志
            string temp;
            bool exchange;
            for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序
            {
                exchange = false; //本趟排序開始前,,交換標(biāo)志應(yīng)為假
                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; //發(fā)生了交換,,故將交換標(biāo)志置為真
                    }
                }
                if (!exchange) //本趟排序未發(fā)生交換,提前終止算法
                {
                    break;
                }
            }
            return r;
        }
        /// <summary>
        /// 生成URL鏈接或加密結(jié)果
        /// </summary>
        /// <param name="para">參數(shù)加密數(shù)組</param>
        /// <param name="_input_charset">編碼格式</param>
        /// <param name="sign_type">加密類型</param>
        /// <param name="key">安全校驗(yàn)碼</param>
        /// <returns>字符串URL或加密結(jié)果</returns>
        public static string CreatUrl(
            //string gateway,//GET方式傳遞參數(shù)時(shí)請(qǐng)去掉注釋
            string[] para,
            string _input_charset,
            string sign_type,
            string key
            )
        {
            int i;
             
            //進(jìn)行排序,;
            string[] Sortedstr = BubbleSort(para);
            //構(gòu)造待md5摘要字符串 ,;
            StringBuilder prestr = new StringBuilder();
            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr.Append(Sortedstr);
                }
                else
                {
                    prestr.Append(Sortedstr + "&");
                }
            }
            prestr.Append(key);
            //生成Md5摘要,;
            string sign = GetMD5(prestr.ToString(), _input_charset);
            //以下是POST方式傳遞參數(shù)
            return sign;
            //以下是GET方式傳遞參數(shù)
            //構(gòu)造支付Url,;
//            char[] delimiterChars = { '='};
//            StringBuilder parameter = new StringBuilder();
//            parameter.Append(gateway);
//            for (i = 0; i < Sortedstr.Length; i++)
//            {//UTF-8格式的編碼轉(zhuǎn)換
//                parameter.Append(Sortedstr.Split(delimiterChars)[0] + "=" + HttpUtility.UrlEncode(Sortedstr.Split(delimiterChars)[1]) + "&");
//            }
//
//            parameter.Append("sign=" + sign + "&sign_type=" + sign_type);
//
//            //返回支付Url,;
//            return parameter.ToString();
        }
        //獲取遠(yuǎn)程服務(wù)器ATN結(jié)果,,驗(yàn)證是否是支付寶服務(wù)器發(fā)來的請(qǐng)求
        public static string Get_Http(string a_strUrl, int timeout)
        {
            string strResult;
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(a_strUrl);
                myReq.Timeout = timeout;
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader sr = new StreamReader(myStream, Encoding.Default);
                StringBuilder strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }
                strResult = strBuilder.ToString();
            }
            catch (Exception exp)
            {
                strResult = "錯(cuò)誤:" + exp.Message;
            }
            return strResult;
        }
    }
}

而我們一般不用管這個(gè)類,只要保證能調(diào)用 的到就行了,,不用管他
我們要做的很少,他是怎么工作的呢,,






這是開發(fā)文檔里的工作圖

其實(shí)我們要處理的只有三個(gè)Aspx的文件,,
先看第一個(gè)吧 Default.aspx
這是一個(gè)請(qǐng)求的界面
[C#] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Gateway;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void BtnAlipay_Click(object sender, EventArgs e)
    {
        //業(yè)務(wù)參數(shù)賦值;
        string gateway = "https://www.alipay.com/cooperate/gateway.do?";    //支付接口
        string service = "create_direct_pay_by_user";                       //服務(wù)名稱,,這個(gè)是識(shí)別是何接口實(shí)現(xiàn)何功能的標(biāo)識(shí),,請(qǐng)勿修改
        string seller_email = "寫自己的";                     //商家簽約時(shí)的支付寶賬號(hào),即收款的支付寶賬號(hào)
        string sign_type = "MD5";                                           //加密類型,簽名方式“不用改”
        string key = "寫自己的";                    //安全校驗(yàn)碼,,與partner是一組,,獲取方式是:用簽約時(shí)支付寶賬號(hào)登陸支付寶網(wǎng)站[url=http://www.alipay.com/]www.alipay.com[/url],在商家服務(wù)我的商家里即可查到,。
        string partner = "寫自己的";                                //商戶ID,,合作身份者ID,合作伙伴ID
        string _input_charset = "utf-8";                                    //編碼類型,,完全根據(jù)客戶自身的項(xiàng)目的編碼格式而定,,千萬不要填錯(cuò)。否則極其容易造成MD5加密錯(cuò)誤,。
        string show_url = "http://www.alipay.com/";                         //展示地址,,即在支付頁面時(shí),商品名稱旁邊的“詳情”的鏈接地址,。
        string out_trade_no = TxtOrderno.Text.Trim();                       //客戶自己的訂單號(hào),,訂單號(hào)必須在自身訂單系統(tǒng)中保持唯一性
        string subject = "4.0系統(tǒng)支付寶充值";                            //商品名稱,也可稱為訂單名稱,,該接口并不是單一的只能買一樣?xùn)|西,,可把一次支付當(dāng)作一次下訂單
        string body = "商戶:" + TxtOrderno.Text.Trim() + "通過支付寶給自己充值:" + TxtTotal_fee.Text.Trim() + "元";                                   //商品描述,即備注
        string total_fee = TxtTotal_fee.Text.Trim();                        //商品價(jià)格,,也可稱為訂單的總金額
        //服務(wù)器通知url(Alipay_Notify.aspx文件所在路經(jīng)),,必須是完整的路徑地址
        string notify_url = [url=http://0.0.6.108/Alipay/Alipay_Notify.aspx;]http://0.0.6.108/Alipay/Alipay_Notify.aspx;[/url]
        //服務(wù)器返回url(Alipay_Return.aspx文件所在路經(jīng)),必須是完整的路徑地址
        string return_url = [url=http://0.0.6.108/Alipay/Alipay_Return.aspx;]http://0.0.6.108/Alipay/Alipay_Return.aspx;[/url]
        //構(gòu)造數(shù)組,;
        //以下數(shù)組即是參與加密的參數(shù),,若參數(shù)的值不允許為空,若該參數(shù)為空,則不要成為該數(shù)組的元素
        string[] para ={
        "service="+service,
        "partner=" + partner,
        "seller_email=" + seller_email,
        "out_trade_no=" + out_trade_no,
        "subject=" + subject,
        "body=" + body,
        "total_fee=" + total_fee,
        "show_url=" + show_url,
        "payment_type=1",
        "notify_url=" + notify_url,
        "return_url=" + return_url,
        "_input_charset="+_input_charset
        };
        //支付URL生成
        string aliay_url = AliPay.CreatUrl(
            //gateway,//GET方式傳遞參數(shù)時(shí)請(qǐng)去掉注釋
            para,
            _input_charset,
            sign_type,
            key
            );
        //以下是GET方式傳遞參數(shù)
        //Response.Redirect(aliay_url);
        //以下是POST方式傳遞參數(shù)
        Response.Write("<form name='alipaysubmit' method='post' action='https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8'>");
        Response.Write("<input type='hidden' name='service' value=" + service + ">");
        Response.Write("<input type='hidden' name='partner' value=" + partner + ">");
        Response.Write("<input type='hidden' name='seller_email' value=" + seller_email + ">");
        Response.Write("<input type='hidden' name='out_trade_no' value=" + out_trade_no + ">");
        Response.Write("<input type='hidden' name='subject' value=" + subject + ">");
        Response.Write("<input type='hidden' name='body' value=" + body + ">");
        Response.Write("<input type='hidden' name='total_fee' value=" + total_fee + ">");
        Response.Write("<input type='hidden' name='show_url' value=" + show_url + ">");
        Response.Write("<input type='hidden' name='return_url' value=" + return_url + ">");
        Response.Write("<input type='hidden' name='notify_url' value=" + notify_url + ">");
        Response.Write("<input type='hidden' name='payment_type' value=1>");
        Response.Write("<input type='hidden' name='sign' value=" + aliay_url + ">");
        Response.Write("<input type='hidden' name='sign_type' value=" + sign_type + ">");
        Response.Write("</form>");
        Response.Write("<script>");
        Response.Write("document.alipaysubmit.submit()");
        Response.Write("</script>");
    }
}


代碼里的key和 partner的獲取方法


現(xiàn)在我們只要按代碼里的信息填寫一樣就可以了,,
然后遠(yuǎn)行網(wǎng)頁
點(diǎn)提交
就會(huì)進(jìn)入



下面的操作就是在支付平臺(tái)的完成了,, 跟咱的程序沒有關(guān)系了
現(xiàn)在我們應(yīng)該想,那付完錢之后呢,?
我們有兩個(gè)界面來處理這個(gè)問題一個(gè)是
Alipay_Return.aspx
[C#] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using Gateway;
/// <summary>
/// 創(chuàng)建該頁面文件時(shí),,請(qǐng)留心該頁面文件是可以對(duì)其進(jìn)行美工處理的,原因在于支付完成以后,,當(dāng)前窗口會(huì)從支付寶的頁面跳轉(zhuǎn)回這個(gè)頁面,。
/// 該頁面稱作“返回頁”,是同步被支付寶服務(wù)器所調(diào)用,,可當(dāng)作是支付完成后的提示信息頁,,如“您的某某某訂單,多少金額已支付成功”,。
/// </summary>
public partial class Alipay_Return : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify";
        //string alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?";//此路徑是在上面鏈接地址無法起作用時(shí)替換使用,。
        string key = "寫自己的"; //partner 的對(duì)應(yīng)交易安全校驗(yàn)碼(必須填寫)
        string partner = "寫自己的";         //partner合作伙伴id(必須填寫)
        string _input_charset = "utf-8";//編碼類型,完全根據(jù)客戶自身的項(xiàng)目的編碼格式而定,,千萬不要填錯(cuò),。否則極其容易造成MD5加密錯(cuò)誤。
        alipayNotifyURL = alipayNotifyURL + "&partner=" + partner + "?ify_id=" + Request.QueryString["notify_id"];
        //獲取支付寶ATN返回結(jié)果,,true是正確的訂單信息,false 是無效的
        string responseTxt = AliPay.Get_Http(alipayNotifyURL, 120000);
        //*******加密簽名程序開始//*******
        int i;
        NameValueCollection coll;
        //Load Form variables into NameValueCollection variable.
        coll = Request.QueryString;
        // Get names of all forms into a string array.
        String[] requestarr = coll.AllKeys;
        //進(jìn)行排序,;
        string[] Sortedstr = AliPay.BubbleSort(requestarr);
        //構(gòu)造待md5摘要字符串 ,;
        StringBuilder prestr = new StringBuilder();
        for (i = 0; i < Sortedstr.Length; i++)
        {
            if (Request.Form[Sortedstr] != "" && Sortedstr != "sign" && Sortedstr != "sign_type")
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr.Append(Sortedstr + "=" + Request.QueryString[Sortedstr]);
                }
                else
                {
                    prestr.Append(Sortedstr + "=" + Request.QueryString[Sortedstr] + "&");
                }
            }
        }
        prestr.Append(key);
        //生成Md5摘要;
        string mysign = AliPay.GetMD5(prestr.ToString(), _input_charset);
        //*******加密簽名程序結(jié)束*******
        string sign = Request.QueryString["sign"];
        //  Response.Write(prestr.ToString());  //調(diào)試用,,支付寶服務(wù)器返回時(shí)的完整路徑,。
        if (mysign == sign && responseTxt == "true")   //驗(yàn)證支付發(fā)過來的消息,簽名是否正確
        {
            //更新自己數(shù)據(jù)庫的訂單語句,,請(qǐng)自己填寫一下
            string strOrderNO = Request.QueryString["out_trade_no"];//訂單號(hào)
            string strPrice = Request.QueryString["total_fee"];//金額
            string strTradeStatus = Request.QueryString["TRADE_STATUS"];//訂單狀態(tài)
            //以下都是自己處理訂單的方法了最后才要輸出如下內(nèi)容
            Response.Write("商戶:" + login[1].ToString().Trim() + "<br>金額:" + strPrice + "   交易成功");     //成功,,可美化該頁面,提示信息
            ////寫文本,,紀(jì)錄支付寶返回消息,,比對(duì)md5計(jì)算結(jié)果(如網(wǎng)站不支持寫txt文件,可改成寫數(shù)據(jù)庫)
            string TOEXCELLR = "MD5結(jié)果:mysign=" + mysign + ",sign=" + sign + ",responseTxt=" + responseTxt + "   交易信息" + "商戶:" + login[1].ToString().Trim() + "<br>金額:" + strPrice + "   交易成功";
            StreamWriter fs = new StreamWriter(Server.MapPath("Return_DATA/" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
            fs.Write(TOEXCELLR);
            fs.Close();
        }
        else
        {
            Response.Write("------------------------------------------");
            Response.Write("<br>Result:responseTxt=" + responseTxt);
            Response.Write("<br>Result:mysign=" + mysign);
            Response.Write("<br>Result:sign=" + sign);
            Response.Write("支付失敗");
            ////寫文本,,紀(jì)錄支付寶返回消息,,比對(duì)md5計(jì)算結(jié)果(如網(wǎng)站不支持寫txt文件,可改成寫數(shù)據(jù)庫)
            string TOEXCELLR = "MD5結(jié)果:mysign=" + mysign + ",sign=" + sign + ",responseTxt=" + responseTxt;
            StreamWriter fs = new StreamWriter(Server.MapPath("Return_DATA/" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
            fs.Write(TOEXCELLR);
            fs.Close();
            //支付失敗,,提示信息
        }
    }
}


這個(gè)是當(dāng)交易成功后要調(diào)用 的界面 在這里只要改動(dòng)一下就行了,, 其實(shí)我們要做的只是改一下這里,只要在這里更新一下你的數(shù)據(jù)庫就行了
[C#] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
//生成對(duì)象
            //OfficeFinanceServices objOfficeFinanceServices = new OfficeFinanceServices();
            //訂單信息
            string[] login = strOrderNO.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
            ////查詢當(dāng)前的余額
            //decimal objdm = objOfficeFinanceServices.OfficeFinanceSelect(Convert.ToInt32(login[0].ToString().Trim()), true);
            //OfficeFinance objofficeFinance = new OfficeFinance();
            //objofficeFinance.ofId = Convert.ToInt32(login[0].ToString().Trim());
            //objofficeFinance.ofOrid = "cz";
            //objofficeFinance.ofTime = DateTime.Now;
            //objofficeFinance.ofType = 1;
            //objofficeFinance.ofAmount = Convert.ToDecimal(strPrice.ToString().Trim());
            //objofficeFinance.ofRemainAmount = Convert.ToDecimal(strPrice.ToString().Trim()) + objdm;
            //objofficeFinance.ofIsCurrentValue = 1;
            //objofficeFinance.ofUserId = -10;
            //objofficeFinance.ofNote1 = "支付寶上帳:" + strPrice.ToString().Trim() + "元";
            //objofficeFinance.ofNote2 = "商戶:" + login[1].ToString().Trim() + "  通過支付寶上帳金額:" + strPrice + "元";
            //objOfficeFinanceServices.addOfficeFinanceOne(objofficeFinance);

大家現(xiàn)在會(huì)問我為什么會(huì)把他們注釋了呢?
我測(cè)試過,,,,這個(gè)界面呢是只到成功的時(shí)候 調(diào)用 一次以后就再不會(huì)調(diào)用 了,
所以這樣有一個(gè)不好的地方 ,,就是有些客戶他們對(duì)轉(zhuǎn)帳操作的很老手,,當(dāng)交易成功之后不等調(diào)用這個(gè)界面就關(guān)閉了瀏覽器,這個(gè)時(shí)候會(huì)出現(xiàn)什么問題呢,?
那支付寶就再也不會(huì)調(diào)用這個(gè)界面 了,,只能等下次交易,錢是打上了,,我們也收到了,,但是就是沒有給客戶充上錢,這個(gè)時(shí)候客戶就會(huì)打電話到公司,,怎么回事啊,, 錢打過去了, 可是我這邊還沒有上帳,,我們上支付寶一看有啊,,但就是沒有上帳 ,怎么辦,,最后只能手動(dòng)給客戶上了,,但又怕他程序再自動(dòng)上一把,呵呵
所以在這里不我建議使用這個(gè)頁面,,如果你只是修改自己的訂單狀態(tài)的話當(dāng)然是可以的
修改余額就不要在這里寫了,,而是寫在這個(gè)Alipay_Notify.aspx頁面里,這個(gè)界面是當(dāng)交易狀態(tài) 發(fā)生變化時(shí)就會(huì)調(diào)用 ,,在沒有收到成功的消息前就會(huì)一直調(diào)用,,
時(shí)效是24小時(shí),這樣的話我們就不用管他是不是轉(zhuǎn)到了成功頁面了,,只要把這個(gè)頁面掛在網(wǎng)上等通知就行了,,
當(dāng)交易成功的時(shí)候上帳 就OK了

[C#] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using Gateway;
using SystemModel;
/// <summary>
/// 創(chuàng)建該頁面文件時(shí),請(qǐng)留心該頁面文件中無任何HTML代碼及空格,。
/// 該頁面稱作“通知頁”,,是異步被支付寶服務(wù)器所調(diào)用。
/// 當(dāng)支付寶的訂單狀態(tài)改變時(shí),,支付寶服務(wù)器則會(huì)自動(dòng)調(diào)用此頁面,,因此請(qǐng)做好自身網(wǎng)站訂單信息與支付寶上的訂單的同步工作
/// </summary>
public partial class Alipay_Notify : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify";
        //string alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?";//此路徑是在上面鏈接地址無法起作用時(shí)替換使用。
        string partner = "寫自己的";         //partner合作伙伴id(必須填寫)
        string key = "寫自己的"; //partner 的對(duì)應(yīng)交易安全校驗(yàn)碼(必須填寫)
        string _input_charset = "utf-8";//編碼類型,,完全根據(jù)客戶自身的項(xiàng)目的編碼格式而定,,千萬不要填錯(cuò),。否則極其容易造成MD5加密錯(cuò)誤。
        alipayNotifyURL = alipayNotifyURL + "&partner=" + partner + "?ify_id=" + Request.Form["notify_id"];
        //獲取支付寶ATN返回結(jié)果,,true是正確的訂單信息,,false 是無效的
        string responseTxt = AliPay.Get_Http(alipayNotifyURL, 120000);
        //*******加密簽名程序開始*******
        int i;
        NameValueCollection coll;
        //Load Form variables into NameValueCollection variable.
        coll = Request.Form;
        // Get names of all forms into a string array.
        String[] requestarr = coll.AllKeys;
        //進(jìn)行排序;
        string[] Sortedstr = AliPay.BubbleSort(requestarr);
        //構(gòu)造待md5摘要字符串 ,;
        StringBuilder prestr = new StringBuilder();
        for (i = 0; i < Sortedstr.Length; i++)
        {
            if (Request.Form[Sortedstr] != "" && Sortedstr != "sign" && Sortedstr != "sign_type")
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr.Append(Sortedstr + "=" + Request.Form[Sortedstr]);
                }
                else
                {
                    prestr.Append(Sortedstr + "=" + Request.Form[Sortedstr] + "&");
                }
            }
        }
        prestr.Append(key);
        string mysign = AliPay.GetMD5(prestr.ToString(), _input_charset);
        //*******加密簽名程序結(jié)束*******
        string sign = Request.Form["sign"];
        if (mysign == sign && responseTxt == "true")   //驗(yàn)證支付發(fā)過來的消息,,簽名是否正確,只要成功進(jìn)如這個(gè)判斷里,,則表示該頁面已被支付寶服務(wù)器成功調(diào)用
        //但判斷內(nèi)出現(xiàn)自身編寫的程序相關(guān)錯(cuò)誤導(dǎo)致通知給支付寶并不是發(fā)送success的消息或沒有更新客戶自身的數(shù)據(jù)庫的情況,,請(qǐng)自身程序編寫好應(yīng)對(duì)措施,否則查明原因時(shí)困難之極
        {
            if (Request.Form["trade_status"] == "WAIT_BUYER_PAY")//   判斷支付狀態(tài)_等待買家付款(文檔中有枚舉表可以參考)           
            {
                //更新自己數(shù)據(jù)庫的訂單語句,請(qǐng)自己填寫一下
                string strOrderNO = Request.Form["out_trade_no"];//訂單號(hào)
                string strPrice = Request.Form["total_fee"];//金額    如果你申請(qǐng)了商家購物卷功能,,在返回信息里面請(qǐng)不要做金額的判斷,否則會(huì)校驗(yàn)通過不了,。
                string TOEXCELL = "MD5結(jié)果:mysign=" + mysign + ",sign=" + sign + ",responseTxt=" + responseTxt;
                StreamWriter f = new StreamWriter(Server.MapPath("Notify_DATA/" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
                f.Write(TOEXCELL + "訂單號(hào):" + strOrderNO.ToString().Trim() + "  金額:" + strPrice.ToString().Trim());
                f.Close();
                //以下是我處理自己的訂單狀態(tài)
                Alipaym objalipay = new Alipaym();
                objalipay.APID = strOrderNO;
                objalipay.addTime = DateTime.Now;
                objalipay.total_fee = Convert.ToDecimal(strPrice);
                objalipay.trade_status = "等待買家付款";
                objalipay.Text1 = DateTime.Now.ToString();
                objalipay.Text2 = "";
                objalipay.Text3 = "";
                objalipay.Text4 = "";
                objalipay.Text5 = "";
                OfficeFinanceServices.Update(objalipay);
            }
            else if (Request.Form["trade_status"] == "TRADE_FINISHED" || Request.Form["trade_status"] == "TRADE_SUCCESS")//   判斷支付狀態(tài)_交易成功結(jié)束(文檔中有枚舉表可以參考)  
            {
                //更新自己數(shù)據(jù)庫的訂單語句,,請(qǐng)自己填寫一下
                string strOrderNO = Request.Form["out_trade_no"];//訂單號(hào)
                string strPrice = Request.Form["total_fee"];//金額 
                //生成對(duì)象
                OfficeFinanceServices objOfficeFinanceServices = new OfficeFinanceServices();
                //訂單信息
                string[] login = strOrderNO.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                ////查詢當(dāng)前的余額
                decimal objdm = objOfficeFinanceServices.OfficeFinanceSelect(Convert.ToInt32(login[0].ToString().Trim()), true);
                OfficeFinance objofficeFinance = new OfficeFinance();
                objofficeFinance.ofId = Convert.ToInt32(login[0].ToString().Trim());
                objofficeFinance.ofOrid = "cz";
                objofficeFinance.ofTime = DateTime.Now;
                objofficeFinance.ofType = 1;
                objofficeFinance.ofAmount = Convert.ToDecimal(strPrice.ToString().Trim());
                objofficeFinance.ofRemainAmount = Convert.ToDecimal(strPrice.ToString().Trim()) + objdm;
                objofficeFinance.ofIsCurrentValue = 1;
                objofficeFinance.ofUserId = -10;
                objofficeFinance.ofNote1 = "支付寶上帳:" + strPrice.ToString().Trim() + "元";
                objofficeFinance.ofNote2 = "商戶:" + login[1].ToString().Trim() + "  通過支付寶上帳金額:" + strPrice + "元";
                if (objOfficeFinanceServices.addOfficeFinanceOne(objofficeFinance))
                {
                    Response.Write("success");
                    Alipaym objalipay = new Alipaym();
                    objalipay.APID = strOrderNO;
                    objalipay.addTime = DateTime.Now;
                    objalipay.total_fee = Convert.ToDecimal(strPrice);
                    objalipay.trade_status = "交易成功";
                    objalipay.Text1 = DateTime.Now.ToString();
                    objalipay.Text2 = "";
                    objalipay.Text3 = "";
                    objalipay.Text4 = "";
                    objalipay.Text5 = "";
                    OfficeFinanceServices.Update(objalipay);
                }
                else
                {
                    Response.Write("fail");
                }
            }
            else
            {
                //更新自己數(shù)據(jù)庫的訂單語句,,請(qǐng)自己填寫一下
            }
            //Response.Write("success");     //返回給支付寶消息,,成功,請(qǐng)不要改寫這個(gè)success
            //success與fail及其他字符的區(qū)別在于,,支付寶的服務(wù)器若遇到success時(shí),,則不再發(fā)送請(qǐng)求通知(即不再調(diào)用該頁面,讓該頁面再次運(yùn)行起來),,
            //若不是success,,則支付寶默認(rèn)沒有收到成功的信息,,則會(huì)反復(fù)不停地調(diào)用該頁面直到失效,,有效調(diào)用時(shí)間是24小時(shí)以內(nèi)。
            ////寫文本,,紀(jì)錄支付寶返回消息,,比對(duì)md5計(jì)算結(jié)果(如網(wǎng)站不支持寫txt文件,可改成寫數(shù)據(jù)庫)
            string TOEXCELLR = "MD5結(jié)果:mysign=" + mysign + ",sign=" + sign + ",responseTxt=" + responseTxt;
            StreamWriter fs = new StreamWriter(Server.MapPath("Notify_DATA/" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
            fs.Write(TOEXCELLR);
            fs.Close();
        }
        else
        {
            Response.Write("fail");
            //寫文本,,紀(jì)錄支付寶返回消息,,比對(duì)md5計(jì)算結(jié)果(如網(wǎng)站不支持寫txt文件,可改成寫數(shù)據(jù)庫)
            string TOEXCELLR = "MD5結(jié)果:mysign=" + mysign + ",sign=" + sign + ",responseTxt=" + responseTxt;
            StreamWriter fs = new StreamWriter(Server.MapPath("Notify_DATA/" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
            fs.Write(TOEXCELLR);
            fs.Close();
        }
    }
}


最好是記錄一下日志文件,,這樣一但出了問題還可以有個(gè)參考的地方
我的代碼寫的有點(diǎn)亂大家可以適當(dāng)?shù)母囊幌拢呛?
短短兩年的時(shí)間,我公司也寫過不少接口方面的東東了,,在這里和大家分享我的心得和體會(huì),,一般人一說到和什么接口對(duì)接可能會(huì)感覺 到很難,或是感覺很利害的樣子,如果是和銀行的接口對(duì)接,那首先想到的就是安全問題,,再就是技術(shù)含量,其實(shí)不然,接口的產(chǎn)生是為了方便雙方的合作,基本沒有聽說過有那兩家公司因?yàn)槌绦驅(qū)?不上而放棄合作的,,基本沒有,,都是其它方面的原因,接口是為了方便對(duì)接和不同公司和程序之間的交互和通信的,,都是為了方便,不是我們想像的那樣難,,高技術(shù)含量,,要說技術(shù)含量吧也是有一些
我根據(jù)自己的開發(fā)心得總結(jié)一下吧

這種方式的做法是,,服務(wù)方提供一個(gè)方法,,但是一般會(huì)在第一個(gè)參數(shù)或是最后一個(gè)參數(shù)驗(yàn)證一下加密串,,這個(gè)加密串一般是用所傳的參數(shù)組合加密而來,最常見的就是MD5加密了,,像支付寶的就是,。我把這一類型的看做是最低級(jí)的一種,因?yàn)檫@種是最不安全的,,只要我知道了你的加密算法和后就可以自己改動(dòng)參數(shù)了
對(duì)于Http的方法最重要的只有一個(gè)方法
[C#] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/// <summary>
   /// 請(qǐng)求指定 URL 資源,,并獲取響應(yīng)結(jié)果
   /// </summary>
   /// <param name="url">需要請(qǐng)求的 URL 資源</param>
   /// <returns>
   /// 響應(yīng)結(jié)果,;
   /// 出現(xiàn)任意異常,均返回字串"Runtime Error"
   /// </returns>
   private string RequestContent(string url)
   {
       string content = string.Empty;
       try
       {
           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
           request.KeepAlive = false;
           HttpWebResponse response = (HttpWebResponse)request.GetResponse();
           StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
           content = reader.ReadToEnd();
           reader.Close();
       }
       catch (Exception)
       {
           content = "Runtime Error";
       }
       return content;
   }

只要我們把要傳的參數(shù)和URL對(duì)接后傳給這 個(gè)方法就算是完事了,,另外在MD5加密是時(shí)間注意對(duì)方是否要區(qū)分大小寫,,最好是把加密串一下子全轉(zhuǎn)成小寫或是大寫的
加密的方法一般如下

[C#] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
/// <summary>
    /// 傳入明文,返回用MD%加密后的字符串
    /// </summary>
    /// <param name="str">要加密的字符串</param>
    /// <returns>用MD5加密后的字符串</returns>
    public static string ToMD5(string str)
    {
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5");
    }

在做這樣的接口的時(shí)候一定要注意一定要驗(yàn)證的地方有三點(diǎn):第一點(diǎn)就是驗(yàn)證加密串了
這里就是把所需要的參數(shù)在本地加一下密然后和服務(wù)端發(fā)來的對(duì)比
第二點(diǎn)就是控制頁面只在首次加載時(shí)執(zhí)行這個(gè)我們可以通過下面的方式來實(shí)現(xiàn)
[C#] 純文本查看 復(fù)制代碼
01
02
03
04
if (!IsPostBack)
        {
            ............
        }

我們只要在IF塊里面寫我們的代碼就可以了
第三點(diǎn)也是最關(guān)鍵的一點(diǎn)那就是驗(yàn)證一下請(qǐng)求過來的DNS或是IP
就是說你要驗(yàn)證一下發(fā)過來請(qǐng)求的來源電腦是不是你的服務(wù)商的DNS或是IP,,如果不是就可以不執(zhí)行程序或是提示為非法操作,,這樣可以防止有人知道了你的加密算法后自己生成一些代碼來高亂你的程序給公司帶來損失,特別是即使到賬的接口,,這一點(diǎn)一定要驗(yàn)證好,,而且在IIS服務(wù)器最好是綁定一下IP,只接收授權(quán)的IP發(fā)來的消息,。這樣基本可以保證安全問題了,。
好了對(duì)于 這種方法我來用一個(gè)Http的例子來演示一下吧

[C#] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using Gateway;
using SystemModel;
/// <summary>
/// 創(chuàng)建該頁面文件時(shí),請(qǐng)留心該頁面文件是可以對(duì)其進(jìn)行美工處理的,,原因在于支付完成以后,,當(dāng)前窗口會(huì)從支付寶的頁面跳轉(zhuǎn)回這個(gè)頁面。
/// 該頁面稱作“返回頁”,,是同步被支付寶服務(wù)器所調(diào)用,,可當(dāng)作是支付完成后的提示信息頁,如“您的某某某訂單,,多少金額已支付成功”,。
/// </summary>
public partial class Alipay_Return : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//生成對(duì)象
OfficeFinanceServices objOfficeFinanceServices = new OfficeFinanceServices();
Alipaym objalipay = new Alipaym();
try
{
string alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify";
//string alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?";//此路徑是在上面鏈接地址無法起作用時(shí)替換使用。
string key = ""; //partner 的對(duì)應(yīng)交易安全校驗(yàn)碼(必須填寫)
string partner = ""; //partner合作伙伴id(必須填寫)
string _input_charset = "utf-8";//編碼類型,,完全根據(jù)客戶自身的項(xiàng)目的編碼格式而定,,千萬不要填錯(cuò)。否則極其容易造成MD5加密錯(cuò)誤,。
alipayNotifyURL = alipayNotifyURL + "&partner=" + partner + "?ify_id=" + Request.QueryString["notify_id"];
//獲取支付寶ATN返回結(jié)果,,true是正確的訂單信息,false 是無效的
string responseTxt = AliPay.Get_Http(alipayNotifyURL, 120000);
//*******加密簽名程序開始//*******
int i;
NameValueCollection coll;
//Load Form variables into NameValueCollection variable.
coll = Request.QueryString;
// Get names of all forms into a string array.
String[] requestarr = coll.AllKeys;
//進(jìn)行排序,;
string[] Sortedstr = AliPay.BubbleSort(requestarr);
//構(gòu)造待md5摘要字符串 ,;
StringBuilder prestr = new StringBuilder();
for (i = 0; i < Sortedstr.Length; i++)
{
if (Request.Form[Sortedstr] != "" && Sortedstr != "sign" && Sortedstr != "sign_type")
{
if (i == Sortedstr.Length - 1)
{
prestr.Append(Sortedstr + "=" + Request.QueryString[Sortedstr]);
}
else
{
prestr.Append(Sortedstr + "=" + Request.QueryString[Sortedstr] + "&");
}
}
}
prestr.Append(key);
//生成Md5摘要;
string mysign = AliPay.GetMD5(prestr.ToString(), _input_charset);
//*******加密簽名程序結(jié)束*******
string sign = Request.QueryString["sign"];
// Response.Write(prestr.ToString()); //調(diào)試用,,支付寶服務(wù)器返回時(shí)的完整路徑,。
if (mysign == sign && responseTxt == "true" && Request.UserHostName == "www.alipay.com") //驗(yàn)證支付發(fā)過來的消息,簽名是否正確
{
//更新自己數(shù)據(jù)庫的訂單語句,,請(qǐng)自己填寫一下
string strOrderNO = Request.QueryString["out_trade_no"];//訂單號(hào)
string strPrice = Request.QueryString["total_fee"];//金額
string strTradeStatus = Request.QueryString["TRADE_STATUS"];//訂單狀態(tài)
string result = objOfficeFinanceServices.CheckNo(strOrderNO.ToString().Trim());
if (result.Trim() == "0")
{
//成功,,可美化該頁面,提示信息
////寫文本,,紀(jì)錄支付寶返回消息,,比對(duì)md5計(jì)算結(jié)果(如網(wǎng)站不支持寫txt文件,,可改成寫數(shù)據(jù)庫)
string TOEXCELLR = "MD5結(jié)果:mysign=" + mysign + ",sign=" + sign +
",responseTxt=" + responseTxt ;
StreamWriter fs = new StreamWriter(Server.MapPath("Return_DATA/" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
fs.Write(TOEXCELLR);
fs.Close();
//修改訂單狀態(tài)
}
else if (result == "-1")
{
//修改訂單狀態(tài)
////寫文本,紀(jì)錄支付寶返回消息,,比對(duì)md5計(jì)算結(jié)果(如網(wǎng)站不支持寫txt文件,,可改成寫數(shù)據(jù)庫)
string TOEXCELLR = "MD5結(jié)果:mysign=" + mysign + ",sign=" + sign + ",responseTxt=" + responseTxt + "perky_" + result.Trim() + Request.UserHostName.Trim() + Request.UserHostAddress.Trim();
StreamWriter fs = new StreamWriter(Server.MapPath("Return_DATA/" + "e" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
fs.Write(TOEXCELLR);
fs.Close();
Response.Write("查詢訂單時(shí)失敗!!! 請(qǐng)確定你是否下單!!!");
}
else
{
//修改訂單狀態(tài)
////寫文本,紀(jì)錄支付寶返回消息,,比對(duì)md5計(jì)算結(jié)果(如網(wǎng)站不支持寫txt文件,,可改成寫數(shù)據(jù)庫)
string TOEXCELLR = "MD5結(jié)果:mysign=" + mysign + ",sign=" + sign + ",responseTxt=" + responseTxt + "perky_" + result.Trim() + Request.UserHostName.Trim() + Request.UserHostAddress.Trim();
StreamWriter fs = new StreamWriter(Server.MapPath("Return_DATA/" + "e" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
fs.Write(TOEXCELLR);
fs.Close();
Response.Write("重復(fù)使用界面無效!!!");
}
}
else
{
Response.Write("------------------------------------------");
Response.Write("<br>Result:responseTxt=" + responseTxt);
Response.Write("<br>Result:mysign=" + mysign);
Response.Write("<br>Result:sign=" + sign);
Response.Write("支付失敗");
////寫文本,紀(jì)錄支付寶返回消息,,比對(duì)md5計(jì)算結(jié)果(如網(wǎng)站不支持寫txt文件,,可改成寫數(shù)據(jù)庫)
string TOEXCELLR = "MD5結(jié)果:mysign=" + mysign + ",sign=" + sign + ",responseTxt=" + responseTxt + Request.UserHostName.Trim() + Request.UserHostAddress.Trim();
StreamWriter fs = new StreamWriter(Server.MapPath("Return_DATA/" + "e" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
fs.Write(TOEXCELLR);
fs.Close();
}
}
catch (Exception ex)
{
////寫文本,紀(jì)錄支付寶返回消息,,比對(duì)md5計(jì)算結(jié)果(如網(wǎng)站不支持寫txt文件,,可改成寫數(shù)據(jù)庫)
string TOEXCELLR = Request.Url.ToString() + " " + ex.Message.ToString() + Request.UserHostName.Trim() + Request.UserHostAddress.Trim();
StreamWriter fs = new StreamWriter(Server.MapPath("Return_DATA/" + "m" + DateTime.Now.ToString().Replace(":", "")) + ".txt", false, System.Text.Encoding.Default);
fs.Write(TOEXCELLR);
fs.Close();
}
}
}
}


Http的方法有的接口還是要帶證書才能實(shí)現(xiàn)的
關(guān)于這一塊的做方法大家請(qǐng)參考一下我的另一個(gè)文章

HttpRequest訪問Https帶有證書并使用WSDL文檔生成代理類方案
應(yīng)該注意的地方


1.驗(yàn)證加密串
2.驗(yàn)證首次加載時(shí)執(zhí)行
3.驗(yàn)證DNS或是IP
4.IIS服務(wù)器綁定IP或是DNS
5.一般要在關(guān)鍵的地方記錄日志文件,或是存入數(shù)據(jù)庫,,要把發(fā)過來的請(qǐng)求原封不動(dòng)的存儲(chǔ)一下,一是方便查對(duì),,二是一但出現(xiàn)問題這就是證據(jù)?。。,?!
6.注意一下官方的加密串有沒有統(tǒng)一大小寫的問題

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,,不代表本站觀點(diǎn),。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,,謹(jǐn)防詐騙,。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào),。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多