paypal

来源:互联网 发布:淘宝土特产店铺介绍 编辑:程序博客网 时间:2024/04/29 06:03

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>
复制代码

 

 

 

 

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();        }
复制代码

 

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

 

 

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


转载:http://www.cnblogs.com/JohnnyYin/p/3408906.html

0 0
原创粉丝点击