.Net整合PayPal的Demo

來源:互聯網
上載者:User

標籤:c   style   class   blog   code   java   

近來項目中需要使用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/ 中建立開發人員類比帳號,為啥?因為開發人員帳號測試不需要收費

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

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

哦,忘記了,建立買家帳號的時候,千萬別忘記儲值哦,儲值金額<10000刀。

 

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

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

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

付款自動返回設定,指的是完成付款之後跳轉到我們自己網站的介面,這個是顯示給使用者看的,而且這個接收介面,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了,再有問題,可以聯絡我。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.