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=""/>
<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实现支付的更多相关文章
- ASP.NET MVC4 微信公众号开发之网页授权(二):通过公众号AppID(应用ID)和AppSecret(应用密钥)取得网页授权openid
ASP.NET MVC4 微信公众号开发之网页授权(一):搭建基础环境 通过了上一篇文章我们已经搭建好了基础开发大环境,现在打开开发环境这里我用的是 vs2013,通过如下方式: 拼接请求链接重定向到 ...
- ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存
ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存 part 1:给我点时间,允许我感慨一下2016年 正好有时间,总结一下最近使用的一些技术,也算是为2016年画上一个完 ...
- CentOS上 Mono 3.2.8运行ASP.NET MVC4经验
周一到周三,折腾了两天半的时间,经历几次周折,在小蝶惊鸿的鼎力帮助下,终于在Mono 3.2.8上运行成功MVC4.在此总结经验如下: 系统平台的版本: CentOS 6.5 Mono 3.2.8 J ...
- ASP.NET MVC4入门到精通系列目录汇总
序言 最近公司在招.NET程序员,我发现好多来公司面试的.NET程序员居然都没有 ASP.NET MVC项目经验,其中包括一些工作4.5年了,甚至8年10年的,许多人给我的感觉是:工作了4.5年,We ...
- [MVC4]ASP.NET MVC4+EF5(Lambda/Linq)读取数据
继续上一节初始ASP.NET MVC4,继续深入学习,感受了一下微软的MVC4+EF5(EntityFramework5)框架的强大,能够高效的开发出网站应用开发系统,下面就看一下如何用MVC4+EF ...
- 教你快速高效接入SDK——服务器端支付回调的处理方式
转载自:http://blog.csdn.net/chenjie19891104/article/details/48321427今天着重把之前渠道服务器端SDK的时候,遇到的一个蛋疼的问题给解决了. ...
- 21、ASP.NET MVC入门到精通——ASP.NET MVC4优化
本系列目录:ASP.NET MVC4入门到精通系列目录汇总 删除无用的视图引擎 默认情况下,ASP.NET MVCE同时支持WebForm和Razor引擎,而我们通常在同一个项目中只用到了一种视图引擎 ...
- 最新版CentOS6.5上安装部署ASP.NET MVC4和WebApi
最新版CentOS6.5上安装部署ASP.NET MVC4和WebApi 使用Jexus5.8.1独立版 http://www.linuxdot.net/ ps:该“独立版”支持64位的CentOS ...
- Asp.Net MVC4 + Oracle + EasyUI 学习 第二章
Asp.Net MVC4 + Oracle + EasyUI 第二章 --使用Ajax提升网站性能 本文链接:http://www.cnblogs.com/likeli/p/4236723.html ...
随机推荐
- string.Format对C#字符串格式化
String.Format 方法的几种定义: String.Format (String, Object) 将指定的 String 中的格式项替换为指定的 Object 实例的值的文本等效项.Stri ...
- 使用JAVA打开本地应用程序相关的文件
在该项目中需要运行本地文件或应用程序,JDK6添加后Desktop类别.可以直接使用.这使得有可能在程序中无论什么应用程序可以打开的.例:打开pdf文件,当地福昕是默认打开.执行程序将使用福昕开放pd ...
- Compare .NET Objects对象比较组件
Compare .NET Objects对象比较组件 阅读目录 1.Compare .NET Objects介绍 2. Compare .NET Objects注意事项 3.一个简单的使用案例 4.三 ...
- 找呀志_使用SQLiteDatabase增删改提供的搜索方法和事务
知识具体解释:http://blog.csdn.net/zhaoyazhi2129/article/details/9026093 MainActivity.java,User.java,BaseDa ...
- crawler_URL编码原理详解
经常写爬虫的童鞋,难免要处理含有中文的url,大部分时间,都知道url_encode,各个语言也都有支持,今天简单整理下原理,供大家科普 1.特征: 如果URL中含有非ASCII字符的话, 浏览器会对 ...
- crawler_网络爬虫之数据分析_httpwatcher
所谓爬虫,首先要通过各种手段爬取到想要站点的数据. web2.0之后,各种网络站点类型越来越多,早期的站点多为静态页面[html .htm],后来逐步加入 jsp.asp,等交互性强的页面.再后来随着 ...
- 前端项目部署之Grunt
如果你的前端项目很小或都者项目不需要通过专门的运维同学走流水线上线部署的话,那么可以略过以下的繁文. ok,Let's go! 我们看看如何使用grunt来部署上线项目? 前端项目一般分为两种类型:T ...
- 批处理获取IP地址
setlocal ENABLEEXTENSIONS & set "i=0.0.0.0" & set "j=" for /f "toke ...
- Asp.net MVC + EF + Spring.Net 项目实践(四)
这篇写一写如何使用Spring.net来解耦各个项目 1. 在接口层添加IStudentBLL文件,里面有GetStudent和GetAllStudents两个方法:然后在StudentBLL类里实现 ...
- iOS开发的一些奇巧淫技2
能不能只用一个pan手势来代替UISwipegesture的各个方向? - (void)pan:(UIPanGestureRecognizer *)sender { typedef NS_ENUM(N ...