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. Spring + Spring MVC + Hibernate

    Spring + Spring MVC + Hibernate项目开发集成(注解) Posted on 2015-05-09 11:58 沐浴未来的我和你 阅读(307) 评论(0) 编辑 收藏 在自 ...

  2. Entity Framework加载相关实体——延迟加载Lazy Loading、贪婪加载Eager Loading、显示加载Explicit Loading

    Entity Framework提供了三种加载相关实体的方法:Lazy Loading,Eager Loading和Explicit Loading.首先我们先来看一下MSDN对三种加载实体方法的定义 ...

  3. 编程算法 - 区间调度问题 代码(C)

    区间调度问题 代码(C) 本文地址: http://blog.csdn.net/caroline_wendy 题目: 有n项工作, 每项工作分别在s时间開始, 在t时间结束. 对于每项工作能够选择參与 ...

  4. 关于”机器学习方法“,&quot;深度学习方法&quot;系列

    "机器学习/深度学习方法"系列,我本着开放与共享(open and share)的精神撰写,目的是让很多其它的人了解机器学习的概念,理解其原理,学会应用.如今网上各种技术类文章非常 ...

  5. my97 日期控件

    官网:http://www.my97.net/   好多广告啊! 文档地址: http://www.mysuc.com/test/My97DatePicker/

  6. Android checkCallingPermission()方法返回值问题

    Android开发检查权限时,发现调用checkCallingPermission()总是返回值-1,而Binder.getCallingPid() == Process.myPid()又总是返回tr ...

  7. 用Iconv应对NodeJs对称加密技术在汉字编码与NoSQL的一些坑洞

    ·起因 汉字编码技术在实际应用中总是会存在这样或者那样的问题,尤其是在一些热门NoSQL方面多少会遇到挑战.比方说Cassandra字符集还不直接支持GB2312,要想存储写汉字那可真是麻烦.当然这还 ...

  8. BZOJ 2120 色彩数 暴力

    标题效果:给定一个序列,两种操作: 1.询[l,r]间隔多少个不同的号码 2.单点变化 n,m<=1W 树盖树?树董事长?因此不必! 暴力之前,这个问题2s,不想复杂!适当的水太! 离散化一下! ...

  9. c#-Artificial Intelligence Class

    NET Artificial Intelligence Class http://www.codeproject.com/KB/recipes/aforge_neuro/neuro_src.zip

  10. JAVA进阶-注解

    注解元数据分为4部分分别为Target,Documented,Inherited,Retention: Target>指定被注解的注解仅仅能使用在某个类型上;ElementType指定其类型:能 ...