ASP.NET Core Web 支付功能接入 支付宝-电脑网页支付篇

时间:2022-12-16 12:44:22

// 随着版本更迭,新版本可能无法完全适用,请参考仓库内的示例。

这篇文章将介绍ASP.NET Core中使用 开源项目 Payment(https://github.com/Essensoft/Payment),实现接入支付宝-电脑网页支付接口及同步跳转及异步通知功能。

开发环境:Win 10 x64、VS2017 15.6.4、.NET Core SDK 2.1.101、.NET Core Runtime 2.0.6

1.新建"ASP.NET Core Web 应用程序"项目,我将它命名为AlipaySample.

ASP.NET Core Web 支付功能接入 支付宝-电脑网页支付篇

ASP.NET Core Web 支付功能接入 支付宝-电脑网页支付篇

2. 引入安装Nuget包 "Essensoft.AspNetCore.Payment.Alipay". 目前(2018/03/29)版本为 1.2.1

ASP.NET Core Web 支付功能接入 支付宝-电脑网页支付篇

ASP.NET Core Web 支付功能接入 支付宝-电脑网页支付篇

3. 在Startup.cs文件内 添加依赖注入、设置参数(蚂蚁金服开放平台 - 账户管理 - 密钥管理 - 开放平台密钥)

代码:

         public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(); // 添加支付宝客户端依赖注入
services.AddAlipay(); // 可在添加依赖注入时设置参数 一般设置 AppId、RsaPrivateKey、RsaPublicKey,其余默认即可.
// 如:
//services.AddAlipay(opt =>
//{
// //此处为蚂蚁金服开放平台上创建的APPID,而非老版本的商户号
// opt.AppId = ""; // // 这里的公私钥 默认均为支付宝官方推荐使用的RSAWithSHA256.
// // 商户私钥
// opt.RsaPrivateKey = "";
// // 支付宝公钥
// opt.RsaPublicKey = "";
//}); // 具体参数见 AlipayOptions // 注册配置实例
services.Configure<AlipayOptions>(Configuration.GetSection("Alipay")); // 两种方式设置注册配置实例参数 // 1.默认配置文件(开发环境/正式环境):
// appsettings.Development.json / appsettings.json // 2.用户机密配置文件(VS2017 15.6.4 中,右键项目 => 管理用户机密):
// Windows: % APPDATA %\microsoft\UserSecrets\< userSecretsId >\secrets.json
// Linux: ~/.microsoft / usersecrets /< userSecretsId >/ secrets.json
// macOS: ~/.microsoft / usersecrets /< userSecretsId >/ secrets.json // 配置文件内容如下('...'为省略的项目其他配置内容,若有的情况下 -_-!): //{
// ...
// ...
//
// "Alipay": {
// "AppId": "",
// "RsaPublicKey": "",
// "RsaPrivateKey": ""
// }
//}
}

4. 添加一个控制器, 我将其命名为 AlipayController.cs

代码:

 using Essensoft.AspNetCore.Payment.Alipay;
using Essensoft.AspNetCore.Payment.Alipay.Domain;
using Essensoft.AspNetCore.Payment.Alipay.Notify;
using Essensoft.AspNetCore.Payment.Alipay.Request;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks; namespace AlipaySample.Controllers
{
public class AlipayController : Controller
{
// 支付宝请求客户端(用于处理请求与其响应)
private readonly AlipayClient _client = null; // 支付宝通知客户端(用于解析异步通知或同步跳转)
private readonly AlipayNotifyClient _notifyClient = null; // 赋值依赖注入对象
public AlipayController(AlipayClient client, AlipayNotifyClient notifyClient)
{
_client = client;
_notifyClient = notifyClient;
} [HttpPost]
public async Task<IActionResult> PagePay(string out_trade_no, string subject, string total_amount, string body, string product_code, string notify_url, string return_url)
{
// 组装模型
var model = new AlipayTradePagePayModel()
{
Body = body,
Subject = subject,
TotalAmount = total_amount,
OutTradeNo = out_trade_no,
ProductCode = product_code,
}; var req = new AlipayTradePagePayRequest(); // 设置请求参数
req.SetBizModel(model); // 设置异步通知URL
req.SetNotifyUrl(notify_url); // 设置同步跳转URL
req.SetReturnUrl(return_url); // 页面请求处理 传入 'GET' 返回的 response.Body 为 URL, 'POST' 返回的 response.Body 为 HTML.
var response = await _client.PageExecuteAsync(req, null, "GET"); // 重定向到支付宝电脑网页支付页面.
return Redirect(response.Body);
} /// <summary>
/// 电脑网页支付-同步跳转
/// 常用于展示订单支付状态页,建议在异步通知统一做业务处理,而不是在此处.
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> PagePayReturn()
{
try
{
// 以 AlipayTradePagePayReturnResponse 类型 解析
var notify = await _notifyClient.ExecuteAsync<AlipayTradePagePayReturnResponse>(Request);
return Content("成功:" + notify.OutTradeNo);
}
catch
{
return Content("参数异常/验签失败");
}
} /// <summary>
/// 电脑网页支付-异步通知
/// 常用于订单业务处理
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> PagePayNotify()
{
try
{
// 以 AlipayTradePagePayNotifyResponse 类型 解析
var notify = await _notifyClient.ExecuteAsync<AlipayTradePagePayNotifyResponse>(Request);
if ("TRADE_SUCCESS" == notify.TradeStatus) // 订单是否交易完成
{
// 业务代码
// ...
// ... //返回给支付宝成功内容,停止继续通知
return Content("success", "text/plain");
}
// 订单其他状态均返回给支付宝空内容.
return NoContent();
}
catch
{
// 参数异常/验签失败均返回给支付宝空内容.
return NoContent();
}
}
}
}

5. 修改 Views/Home/Index 页面,用于网站提交支付请求.

代码:

 @{
ViewData["Title"] = "Home Page";
} <div style="padding:24px 0">
<h3>支付宝 电脑网站支付 - <a href="https://docs.open.alipay.com/270/alipay.trade.page.pay" target="_blank">API文档</a></h3>
<hr />
<form asp-controller="Alipay" asp-action="PagePay" target="_blank">
<div class="form-group">
<label>body:</label>
<input type="text" class="form-control" name="body" value="支付宝网站支付测试详情">
</div>
<div class="form-group">
<label>subject:</label>
<input type="text" class="form-control" name="subject" value="支付宝网站支付测试">
</div>
<div class="form-group">
<label>total_amount:</label>
<input type="text" class="form-control" name="total_amount" value="0.01">
</div>
<div class="form-group">
<label>out_trade_no:</label>
<input type="text" class="form-control" name="out_trade_no" value="@DateTime.Now.ToString("yyyyMMddHHmmssfff")">
</div>
<div class="form-group">
<label>product_code:</label>
<input type="text" class="form-control" name="product_code" value="FAST_INSTANT_TRADE_PAY">
</div>
<div class="form-group">
<label>notify_url(通知Url需外网环境可访问):</label>
<input type="text" class="form-control" name="notify_url" value="http://xxx.com/alipay/pagepaynotify">
</div>
<div class="form-group">
<label>return_url:</label>
<input type="text" class="form-control" name="return_url" value="http://xxx.com/alipay/pagepayreturn">
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
</div>

实现页面如下:

ASP.NET Core Web 支付功能接入 支付宝-电脑网页支付篇

有疑问可以在 https://github.com/Essensoft/Payment 提交Issue ,也可以加入Payment 交流群:522457525

本篇文章到此结束,具体效果可自行测试。感谢各位观看。