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. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(20)-多条件模糊查询和回收站还原的实现

    原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(20)-多条件模糊查询和回收站还原的实现 ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇)   (1):框架 ...

  2. 1213 How Many Tables(简单并查集)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1213 简单并查集,统计单独成树的数量. 代码: #include <stdio.h> #i ...

  3. 接收终端Request.InputStream阅读

    接收终端Request.InputStream阅读请求页面参数,最后字符串. byte[] byts = new byte[HttpContext.Current.Request.InputStrea ...

  4. 蓝桥杯 BASIC 27 矩阵乘法(矩阵、二维数组)

    [思路]:注意0次幂是单位矩阵. [AC代码]: #include <iostream> #include <algorithm> #include <iomanip&g ...

  5. Advance Installer安装问题

    一,在Advance Installer中注冊dll 1,首先将文件加入到Files And Folders中.此处以InstallValidate.dll为例. 2,在Custom Action处进 ...

  6. 修改 dll

    由于没有源码,想改dll,就要依靠反汇编了. 输入 ildasm.exe 据说也可以直接 C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin 找到该软件 ...

  7. 代理模式与Android

    代理模式(Proxy) 一.   什么是代理模式 先来看看官方的说法,代理模式就是为其它对象提供一种代理,以控制对这个对象的訪问. 看来这个官方的说法的确有点官方,看了还是让人感觉不点不知所措,还是不 ...

  8. Unofficial Microsoft SQL Server Driver for PHP (sqlsrv)非官方的PHP SQL Server 驱动

    原文 Unofficial Microsoft SQL Server Driver for PHP (sqlsrv) Here are unofficial modified builds of Mi ...

  9. Appium0.18.x迁移到Appium1.x须知事项

    英文原版:https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/migrating-to-1-0.md Migr ...

  10. Linux下防火墙设置

    Linux下开启/关闭防火墙命令  1) 永久性生效,重启后不会复原 开启:chkconfigiptables on 关闭:chkconfigiptables off 2) 即时生效,重启后复原 开启 ...