• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

asp.netmvc4运用paypalsdk实现支付

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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方法进行支付。支付成功后再去看看付款的账号的余额和收款账号的余额。

 

 

以同样的方式去查看收款账号是否收到钱,整个过程结束。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
asp.netdatatable的用法发布时间:2022-07-10
下一篇:
ASP.NET的CMS发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap