天天看點

.Net內建PayPal的Demo

近來項目中需要使用Paypal(貝寶)支付,研究了一下接口,真是吐血,花了一個下午+一個晚上,屢敗屢戰,海淘了若幹文檔,終于嘗試成功了,分享一下,希望對将要使用paypal的朋友有所幫助。

paypal提供3種類型的對外付款接口,可參考:https://cms.paypal.com/c2/cgi-bin/?cmd=_render-content&content_ID=pages_c2/profile_comparison_new&fli=true

我們這裡采用标準的網頁版本,其中标準的網頁版本又分為三種實作方式:

1.按鈕方式,也就是一個商品一個按鈕

2.購物車方式,讓paypal托管你的購物車

3.你自己的購物網站有購物車,付款時候将購物車資料送出到paypal即可付款

考慮自由度問題,當然我們需要第三種方式。

準備工作

1.到www.paypal.com中申請一個正式的賬号,注意銀行卡目前隻能用信用卡和借記卡,并且需要支援不同币種的,否則可能開通失敗。

2.用剛才申請的賬号到https://developer.paypal.com/ 中建立開發者模拟賬号,為啥?因為開發者賬号測試不需要收費

這裡需要建立兩個賬号,買家和賣家,預設系統會給你建立賣家的。

.Net內建PayPal的Demo

賬号建立好了之後,注意修改每個賬号的登入密碼,在profile裡改。

哦,忘記了,建立買家賬号的時候,千萬别忘記充值哦,充值金額<10000刀。

3.設定好了之後,我們到沙箱裡登入賣家賬号,單擊連結 Enter Sandbox site,用Business類型賬号登入,然後做如下設定

.Net內建PayPal的Demo
.Net內建PayPal的Demo
.Net內建PayPal的Demo

 IPN即時付款通知的意義是什麼呢?互動原理如下:

我們送出購物車到paypal,完成付款以後,paypal會想我們設定好的IPN代理,發送消息,進而使我們自己的程式得知是否付款成功,以備後續操作,而且這個操作是在背景調用的,其主要目的就是為了防止使用者主動關閉浏覽器,造成程式訂單狀态無法更新的問題。

.Net內建PayPal的Demo

付款自動傳回設定,指的是完成付款之後跳轉到我們自己網站的界面,這個是顯示給使用者看的,而且這個接收界面,paypal會發送相關訂單資料,付款狀态等到這個頁面上,也就是“付款資料傳輸(可選)”這項,勾上之後在傳回URL界面就可接收到相關資料了(使用者付款完成後,惡意關閉的情況除外)

4.當然上面兩個值在賬号裡面設定是全局的,你可以在具體的送出按鈕裡面設定

5.在我們的購物網站,實作購物車界面代碼:

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
        <input type="hidden" name="cmd" value="_cart">
        <input type="hidden" name="upload" value="1">
        <input type="hidden" name="business" value="[email protected]">

        <input type="hidden" name="item_name_1" value="San Francisco Bay(32'X32')">
        <input type="hidden" name="amount_1" value="1.00">
        <input type="hidden" name="quantity_1" value="2">

        <input type="hidden" name="item_name_2" value="Mount Hamilton(24'x15')">
        <input type="hidden" name="amount_2" value="1.00">
        <input type="hidden" name="quantity_2" value="1">

        <input type="hidden" name="currency_code" value="CNY">
     <!--這裡重寫url,将覆寫全局設定-->
        <input type="hidden" name="return" value="http://127.0.0.1:56508/ok.aspx">
        <input type="Hidden" name="notify_url" value="http://127.0.0.1:56508/pp.aspx" />

        <input type="submit" value="Upload Cart" alt="Make payments with PayPal-it's fastfree and secure!" />
    </form>      

6.付款成功界面代碼,也就是return

string strFormValues = Request.Params.ToString();
            string strNewValue;
            string strResponse;
            string serverURL = "https://www.sandbox.paypal.com/cgi-bin/webscr";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(serverURL);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            strNewValue = "cmd=_notify-validate";
            strNewValue = "cmd=_notify-synch&tx=" + Request.QueryString["tx"] + "&at=access_token你的";
            //req.ContentLength = strNewValue.Length;

            StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            stOut.Write(strNewValue);
            stOut.Close();

            StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
            strResponse = stIn.ReadToEnd();
            stIn.Close();
            if (strResponse.StartsWith("SUCCESS"))
            {
            }
            else
            {
            }      

 7.IPN背景資料接收

//Post back to either sandbox or live
        string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
        string strLive = "https://www.paypal.com/cgi-bin/webscr";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);

        //Set values for the request back
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
        string strRequest = Encoding.ASCII.GetString(param);
        string ipnPost = strRequest;
        strRequest += "&cmd=_notify-validate";
        req.ContentLength = strRequest.Length;

        //for proxy
        //WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
        //req.Proxy = proxy;

        //Send the request to PayPal and get the response
        StreamWriter streamOut = new StreamWriter(req.GetRequestStream(),
                                 System.Text.Encoding.ASCII);
        streamOut.Write(strRequest);
        streamOut.Close();

        StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
        string strResponse = streamIn.ReadToEnd();
        streamIn.Close();

        // logging ipn messages... be sure that you give write
        // permission to process executing this code
        string logPathDir = ResolveUrl("");
        string logPath = string.Format("{0}\\{1}.txt",
                         Server.MapPath(logPathDir), DateTime.Now.Ticks);
        File.WriteAllText(logPath, ipnPost + " " + strResponse);
        //

        if (strResponse == "VERIFIED")
        {
            //check the payment_status is Completed
            //check that txn_id has not been previously processed
            //check that receiver_email is your Primary PayPal email
            //check that payment_amount/payment_currency are correct
            //process payment
        }
        else if (strResponse == "INVALID")
        {
            //log for manual investigation
        }
        else
        {
            //log response/ipn data for manual investigation
        }
        Response.Write(strResponse);      

8.最後聽我一言,程式寫好了之後,一定要釋出到公網iis上,再測試,不然IPN永遠都是INVALID,就是這個鳥問題讓我搞了一個晚上,氣死了。 

ok了,再有問題,可以聯系我。

Demo下載下傳位址:https://files.cnblogs.com/qidian10/PayPal-Demo%26SDK.rar

.Net內建PayPal的Demo

作者:Jack.Chain

出處:http://www.cnblogs.com/qidian10