asp.net mvc4 運用 paypal sdk實現支付


1.https://developer.paypal.com/ 注冊賬號,並且申請一個app,獲得 client id,secret等數據

 

 

 

2.點擊頁面中"Sandbox Account"按鈕,創建至少兩個賬號(一個收錢用,一個付錢用),paypal中sandbox是測試環境。live是上線后的環境。

 

 

 

3.下載paypal sdk for .net,https://github.com/paypal/rest-api-sdk-dotnet

 

 

4.新建一個解決方案(本例為mvc4 web程序:Paypalsample),根據需求選擇適合的SDK文件,或者還可以通過NuGet(如果你的vs帶有此功能)的方式來添加SDK,以下是vs2012的添加過程

 

 

 

 

 

 

 

 

5.OK,paypal SDK加進來了,接下來要對web.config文件進行配置,參考地址:https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters#list-of-configuration-parameters

 <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="paypal" type="PayPal.Manager.SDKConfigHandler, PayPalCoreSDK"/>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <!-- PayPal SDK config -->
  <paypal>
    <settings>
      <!--<add name="endpoint" value="https://api.sandbox.paypal.com"/>-->
      <add name="mode" value="sandbox" /><!--or set value "live" -->
      <add name="connectionTimeout" value="360000"/>
      <add name="requestRetries" value="1"/>
      <add name="ClientID" value="AU0OwhDpDM05PVDfyhm3qpgdXfIc0hNv2O_HaaXbHhA_BvZgwD6sbVloijMW"/>
      <add name="ClientSecret" value="EM3wHxDSvX3QTRKxPMZKHmBtjxYQtscVzzimbnD7FWx7aE0kJ6H5srmvtyZ0"/>
    </settings>
  </paypal>

  <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="RestApiSDKUnitTestLog.log"/>
      <appendToFile value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] %message%newline"/>
      </layout>
    </appender>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="FileAppender"/>
    </root>
  </log4net>
View Code

 

 

 

 

6.接下來就是調用Paypal API實現支付,上文中提到下載SDK,其中有sample的例子,可以參考看看,里面實現了大部分常用的api,本例只實現支付的功能。

   a.(視圖)頁面1部分:

@{
    ViewBag.Title = "Index";
}

<a href="@Url.Action("Payment")">Payment with Paypal account</a>

   b.頁面2部分:

@{
    ViewBag.Title = "Payment";
}

<h1>Payment Status: @ViewBag.Status</h1>


   c.(controller)頁面2后台代碼部分:

 

public ActionResult Payment()
        {
            //get access token
            string accessToken = null;
            string clientID = ConfigManager.Instance.GetProperties()["ClientID"];
            string clientSecret = ConfigManager.Instance.GetProperties()["ClientSecret"];
            OAuthTokenCredential TokenCredential = new OAuthTokenCredential(clientID, clientSecret);
            accessToken = TokenCredential.GetAccessToken();

            Payment pymnt = null;

            // ## ExecutePayment
            if (Request.Params["PayerID"] != null)
            {
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                {
                    pymnt.id = (string)Session[Request.Params["guid"]];
                    try
                    {
                        PaymentExecution pymntExecution = new PaymentExecution();
                        pymntExecution.payer_id = Request.Params["PayerID"];

                        Payment executedPayment = pymnt.Execute(accessToken, pymntExecution);
                        ViewBag.Status = executedPayment.state;
                    }
                    catch (PayPal.Exception.PayPalException ex)
                    {

                    }
                }
            }

            // ## Creating Payment
            else
            {
                // ###Items
                // Items within a transaction.
                Item item = new Item();
                item.name = "筆記本電腦";
                item.currency = "USD";
                item.price = "1000";
                item.quantity = "5";
                item.sku = "";

                List<Item> itms = new List<Item>();
                itms.Add(item);
                ItemList itemList = new ItemList();
                itemList.items = itms;

                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var guid = Convert.ToString(rndm.Next(100000));

                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/";

                // # Redirect URLS
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "guid=" + guid;
                redirUrls.return_url = baseURI + "Payment?guid=" + guid;

                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                details.tax = "10";
                details.shipping = "10";
                details.subtotal = "5000";

                // ###Amount
                // Let's you specify a payment amount.
                Amount amnt = new Amount();
                amnt.currency = "USD";
                // Total must be equal to sum of shipping, tax and subtotal.
                amnt.total = "5020";
                amnt.details = details;

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it. 
                List<Transaction> transactionList = new List<Transaction>();
                Transaction tran = new Transaction();
                tran.description = "Transaction description.";
                tran.amount = amnt;
                tran.item_list = itemList;
                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(tran);

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                pymnt = new Payment();
                pymnt.intent = "sale";
                pymnt.payer = payr;
                pymnt.transactions = transactionList;
                pymnt.redirect_urls = redirUrls;

                try
                {
                    string approvalUrl = "";
                    Payment createdPayment = pymnt.Create(accessToken);

                    var links = createdPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            approvalUrl = lnk.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    if (!string.IsNullOrEmpty(approvalUrl))
                        return Redirect(approvalUrl);
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                }
            }
            return View();
        }
View Code

 

c.注意return_url的正確性,總錢數和分項目的錢數要對到,total=subtotal+shipping+tax.其中有些字段非必須,詳細參考官方api:https://developer.paypal.com/webapps/developer/docs/api/#create-a-payment

 

7.運行調試

 

 

付款成功后payment status字段的值會有所變化,此支付方式分成兩個步驟,第一是create payment,創建一個支付清單,然后用戶輸入用戶名和密碼進行支付確認,然后執行ExecutePayment方法進行支付。支付成功后再去看看付款的賬號的余額和收款賬號的余額。

 

 

以同樣的方式去查看收款賬號是否收到錢,整個過程結束。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM