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=""/>
<add name="requestRetries" value=""/>
<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 = "";
item.quantity = "";
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()); 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 = "";
details.shipping = "";
details.subtotal = ""; // ###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 = "";
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方法进行支付。支付成功后再去看看付款的账号的余额和收款账号的余额。

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

asp.net mvc4 运用 paypal sdk实现支付的更多相关文章

  1. ASP.NET MVC4 微信公众号开发之网页授权(二):通过公众号AppID(应用ID)和AppSecret(应用密钥)取得网页授权openid

    ASP.NET MVC4 微信公众号开发之网页授权(一):搭建基础环境 通过了上一篇文章我们已经搭建好了基础开发大环境,现在打开开发环境这里我用的是 vs2013,通过如下方式: 拼接请求链接重定向到 ...

  2. ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存

    ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存 part 1:给我点时间,允许我感慨一下2016年 正好有时间,总结一下最近使用的一些技术,也算是为2016年画上一个完 ...

  3. CentOS上 Mono 3.2.8运行ASP.NET MVC4经验

    周一到周三,折腾了两天半的时间,经历几次周折,在小蝶惊鸿的鼎力帮助下,终于在Mono 3.2.8上运行成功MVC4.在此总结经验如下: 系统平台的版本: CentOS 6.5 Mono 3.2.8 J ...

  4. ASP.NET MVC4入门到精通系列目录汇总

    序言 最近公司在招.NET程序员,我发现好多来公司面试的.NET程序员居然都没有 ASP.NET MVC项目经验,其中包括一些工作4.5年了,甚至8年10年的,许多人给我的感觉是:工作了4.5年,We ...

  5. [MVC4]ASP.NET MVC4+EF5(Lambda/Linq)读取数据

    继续上一节初始ASP.NET MVC4,继续深入学习,感受了一下微软的MVC4+EF5(EntityFramework5)框架的强大,能够高效的开发出网站应用开发系统,下面就看一下如何用MVC4+EF ...

  6. 教你快速高效接入SDK——服务器端支付回调的处理方式

    转载自:http://blog.csdn.net/chenjie19891104/article/details/48321427今天着重把之前渠道服务器端SDK的时候,遇到的一个蛋疼的问题给解决了. ...

  7. 21、ASP.NET MVC入门到精通——ASP.NET MVC4优化

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 删除无用的视图引擎 默认情况下,ASP.NET MVCE同时支持WebForm和Razor引擎,而我们通常在同一个项目中只用到了一种视图引擎 ...

  8. 最新版CentOS6.5上安装部署ASP.NET MVC4和WebApi

    最新版CentOS6.5上安装部署ASP.NET MVC4和WebApi 使用Jexus5.8.1独立版 http://www.linuxdot.net/ ps:该“独立版”支持64位的CentOS ...

  9. Asp.Net MVC4 + Oracle + EasyUI 学习 第二章

    Asp.Net MVC4 + Oracle + EasyUI 第二章 --使用Ajax提升网站性能 本文链接:http://www.cnblogs.com/likeli/p/4236723.html ...

随机推荐

  1. ShellExecuteEx的使用方法

    关于怎样在c++中启动外部的exe程序,之前看到在百度一搜就看到了: ShellExecute(this->m_hWnd,"open","calc.exe" ...

  2. MSSQL发现第五到数据的第十

    第二十数据查询数据库,第十条数据,两起案件: 1,ID是连接的,当然这样的情况比較好查.直接SELECT就能够了.取ID大于5小于10就能够了, 这样的情况比較少. 2.ID不是连接的.假设要取第五条 ...

  3. nolock引发

      Sql Server之旅——终点站 nolock引发的三级事件的一些思考   曾今有件事情让我记忆犹新,那年刚来携程不久,马上就被安排写一个接口,供企鹅公司调用他们员工的差旅信息,然后我就三下五除 ...

  4. nginx的五种负载算法模式

    nginx 负载均衡5种配置方式 1.轮询(默认) 每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除. 2.weight  指定轮询几率,weight和访问比率成正比 ...

  5. Linux学习笔记——怎样在交叉编译时使用共享库

    0.前言     在较为复杂的项目中会利用到交叉编译得到的共享库(*.so文件).在这样的情况下便会产生下面疑问,比如:     [1]交叉编译时的共享库是否须要放置于目标板中,假设须要放置在哪个文件 ...

  6. JavaScript时间工具类

    /** * JavaScript日期工具类 * @author ZhangLp */ /** * 获取当前月的第一天 */ function getCurrentMonthFirst(){ var d ...

  7. 你要知道的C与C++的区别

    原文:你要知道的C与C++的区别 如果要说C和C++的区别的话,可能可以列出很多方面出来,但是有许多方面的区别是我们学完这两门语言之后就可以 很好的理解和区分的,比如C是面向过程的一门编程语言,C++ ...

  8. 【POJ3037】Skiing 最短路

    题意: 有个n*m的滑雪场,bessie要从(1,1)滑到(n,m),问最小时间. 起始有一个速度v,然后每从一个点A到一个点B(仅仅能上下左右走,每次一格),速度就会乘上2^(权值A-权值B). 然 ...

  9. 使用python的Flask实现一个RESTful API服务器端

    使用python的Flask实现一个RESTful API服务器端 最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文 ...

  10. HEAP CORRUPTION DETECTED

    发生主要是由于这个问题给写入超出预分配的空间,注意检查越界情况 版权声明:本文博客原创文章,博客,未经同意,不得转载.