ASP.NET Core Web 支付功能接入 微信-扫码支付篇
2018-03-28 00:00
567 查看
这篇文章将介绍ASP.NET Core中使用 开源项目 Payment,实现接入微信-扫码支付及异步通知功能。开发环境:Win 10 x64、VS2017 15.6.4、.NET Core SDK 2.1.101、.NET Core Runtime 2.0.61.新建"ASP.NET Core Web 应用程序"项目,我将它命名为WeChatPaySample.
2. 引入安装Nuget包 "Essensoft.AspNetCore.WeChatPay". 目前(2018/03/23)版本为 1.1.0
3. 在Startup.cs文件内 添加依赖注入、设置参数(微信支付商户平台 - API安全)代码:public void ConfigureServices(IServiceCollection services) { services.AddMvc();
// 添加微信支付客户端依赖注入 services.AddWeChatPay();
// 可在添加依赖注入时设置参数 一般设置 AppId、MchId、Key,其余默认即可. // 退款、转账等需要双向证书的API 需要配置 Certificate 参数,将.p12证书文件转成base64串写入即可. // 如: //services.AddWeChatPay(opt => //{ // // 此处为 公众号AppId、小程序AppId、企业号corpid、微信开放平台应用AppId // opt.AppId = "";
// // 微信支付商户号 // opt.MchId = "";
// // API密钥 // opt.Key = "";
// // .p12证书文件的base64串 // opt.Certificate = ""; //});
// 具体参数见 WeChatPayOptions
// 注册配置实例 services.Configure<WeChatPayOptions>(Configuration.GetSection("WeChatPay"));
// 两种方式设置注册配置实例参数
// 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
// 配置文件内容如下('...'为省略的项目其他配置内容,若有的情况下 -_-!):
//{ // ... // ... // // "WeChatPay": { // "AppId": "", // "MchId": "", // "Key": "" // "Certificate": "" // } //} }4. 添加一个控制器, 我将其命名为 WeChatPayController.cs代码:using Essensoft.AspNetCore.WeChatPay;using Essensoft.AspNetCore.WeChatPay.Notify;using Essensoft.AspNetCore.WeChatPay.Request;using Microsoft.AspNetCore.Mvc;using System.Threading.Tasks;
namespace WeChatPaySample.Controllers{ public class WeChatPayController : Controller { // 微信支付请求客户端(用于处理请求与其响应) private readonly WeChatPayClient _client = null;
// 微信证书请求客户端(用于处理双向证书请求与其响应) // private readonly WeChatPayCertificateClient _certClient = null;
// 微信支付通知客户端(用于解析异步通知) private readonly WeChatPayNotifyClient _notifyClient = null;
// 赋值依赖注入对象 public WeChatPayController(WeChatPayClient client, WeChatPayNotifyClient notifyClient) { _client = client; _notifyClient = notifyClient; }
/// <summary> /// 统一下单 /// </summary> /// <param name="out_trade_no"></param> /// <param name="body"></param> /// <param name="total_fee"></param> /// <param name="spbill_create_ip"></param> /// <param name="notify_url"></param> /// <param name="trade_type"></param> /// <param name="openid"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> UnifiedOrder(string out_trade_no, string body, int total_fee, string spbill_create_ip, string notify_url, string trade_type, string product_id, string openid) { var request = new WeChatPayUnifiedOrderRequest() { OutTradeNo = out_trade_no, Body = body, TotalFee = total_fee, SpbillCreateIp = spbill_create_ip, NotifyUrl = notify_url, TradeType = trade_type, ProductId = product_id, OpenId = openid, };
// 发起请求 var response = await _client.ExecuteAsync(request);
// 将response.CodeUrl生成为二维码即可使用.
return Ok(response.Body); }
/// <summary> /// 支付结果通知 /// </summary> /// <returns></returns> [HttpPost] public async Task<IActionResult> Notify() { try { // 以 WeChatPayUnifiedOrderNotifyResponse 类型 解析请求 var notify = await _notifyClient.ExecuteAsync<WeChatPayUnifiedOrderNotifyResponse>(Request); if (!notify.IsError) { if (notify.ResultCode == "SUCCESS") { // 业务代码 // ... // ...
//返回给微信支付成功内容,停止继续通知 return Content("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>", "text/xml"); } }
// 订单其他状态均返回给微信支付空内容. return NoContent(); } catch { // 参数异常/验签失败均返回给微信支付空内容. return NoContent(); } }
}}5. 修改 Views/Home/Index 页面,用于网站提交支付请求.代码:@{ ViewData["Title"] = "Home Page";}
<div style="padding:24px 0"> <h3>微信支付 扫码支付 - <a href="https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1" target="_blank">API文档</a></h3> <hr /> <form asp-controller="WeChatPay" asp-action="UnifiedOrder" target="_blank"> <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>body:</label> <input type="text" class="form-control" name="body" value="微信扫码支付测试详情"> </div> <div class="form-group"> <label>total_fee:</label> <input type="text" class="form-control" name="total_fee" value="1"> </div> <div class="form-group"> <label>spbill_create_ip:</label> <input type="text" class="form-control" name="spbill_create_ip" value="127.0.0.1"> </div> <div class="form-group"> <label>notify_url(通知Url需外网环境可访问):</label> <input type="text" class="form-control" name="notify_url" value="http://xxx.com/wechatpay/notify"> </div> <div class="form-group"> <label>trade_type:</label> <input type="text" class="form-control" name="trade_type" value="NATIVE"> </div> <div class="form-group"> <label>product_id:</label> <input type="text" class="form-control" name="product_id" value="@DateTime.Now.ToString("yyyyMMddHHmmssfff")"> </div> <button type="submit" class="btn btn-primary">提交</button> </form></div>实现页面如下:
有疑问可以在 https://github.com/Essensoft/Payment 提交Issue ,也可以加入Payment 交流群:522457525本篇文章到此结束,具体效果可自行测试。感谢各位观看。原文地址:http://www.cnblogs.com/essenroc/p/8630730.html.NET社区新闻,深度好文,欢迎访问公众号文章汇总 http://www.csharpkit.com
2. 引入安装Nuget包 "Essensoft.AspNetCore.WeChatPay". 目前(2018/03/23)版本为 1.1.0
3. 在Startup.cs文件内 添加依赖注入、设置参数(微信支付商户平台 - API安全)代码:public void ConfigureServices(IServiceCollection services) { services.AddMvc();
// 添加微信支付客户端依赖注入 services.AddWeChatPay();
// 可在添加依赖注入时设置参数 一般设置 AppId、MchId、Key,其余默认即可. // 退款、转账等需要双向证书的API 需要配置 Certificate 参数,将.p12证书文件转成base64串写入即可. // 如: //services.AddWeChatPay(opt => //{ // // 此处为 公众号AppId、小程序AppId、企业号corpid、微信开放平台应用AppId // opt.AppId = "";
// // 微信支付商户号 // opt.MchId = "";
// // API密钥 // opt.Key = "";
// // .p12证书文件的base64串 // opt.Certificate = ""; //});
// 具体参数见 WeChatPayOptions
// 注册配置实例 services.Configure<WeChatPayOptions>(Configuration.GetSection("WeChatPay"));
// 两种方式设置注册配置实例参数
// 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
// 配置文件内容如下('...'为省略的项目其他配置内容,若有的情况下 -_-!):
//{ // ... // ... // // "WeChatPay": { // "AppId": "", // "MchId": "", // "Key": "" // "Certificate": "" // } //} }4. 添加一个控制器, 我将其命名为 WeChatPayController.cs代码:using Essensoft.AspNetCore.WeChatPay;using Essensoft.AspNetCore.WeChatPay.Notify;using Essensoft.AspNetCore.WeChatPay.Request;using Microsoft.AspNetCore.Mvc;using System.Threading.Tasks;
namespace WeChatPaySample.Controllers{ public class WeChatPayController : Controller { // 微信支付请求客户端(用于处理请求与其响应) private readonly WeChatPayClient _client = null;
// 微信证书请求客户端(用于处理双向证书请求与其响应) // private readonly WeChatPayCertificateClient _certClient = null;
// 微信支付通知客户端(用于解析异步通知) private readonly WeChatPayNotifyClient _notifyClient = null;
// 赋值依赖注入对象 public WeChatPayController(WeChatPayClient client, WeChatPayNotifyClient notifyClient) { _client = client; _notifyClient = notifyClient; }
/// <summary> /// 统一下单 /// </summary> /// <param name="out_trade_no"></param> /// <param name="body"></param> /// <param name="total_fee"></param> /// <param name="spbill_create_ip"></param> /// <param name="notify_url"></param> /// <param name="trade_type"></param> /// <param name="openid"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> UnifiedOrder(string out_trade_no, string body, int total_fee, string spbill_create_ip, string notify_url, string trade_type, string product_id, string openid) { var request = new WeChatPayUnifiedOrderRequest() { OutTradeNo = out_trade_no, Body = body, TotalFee = total_fee, SpbillCreateIp = spbill_create_ip, NotifyUrl = notify_url, TradeType = trade_type, ProductId = product_id, OpenId = openid, };
// 发起请求 var response = await _client.ExecuteAsync(request);
// 将response.CodeUrl生成为二维码即可使用.
return Ok(response.Body); }
/// <summary> /// 支付结果通知 /// </summary> /// <returns></returns> [HttpPost] public async Task<IActionResult> Notify() { try { // 以 WeChatPayUnifiedOrderNotifyResponse 类型 解析请求 var notify = await _notifyClient.ExecuteAsync<WeChatPayUnifiedOrderNotifyResponse>(Request); if (!notify.IsError) { if (notify.ResultCode == "SUCCESS") { // 业务代码 // ... // ...
//返回给微信支付成功内容,停止继续通知 return Content("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>", "text/xml"); } }
// 订单其他状态均返回给微信支付空内容. return NoContent(); } catch { // 参数异常/验签失败均返回给微信支付空内容. return NoContent(); } }
}}5. 修改 Views/Home/Index 页面,用于网站提交支付请求.代码:@{ ViewData["Title"] = "Home Page";}
<div style="padding:24px 0"> <h3>微信支付 扫码支付 - <a href="https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1" target="_blank">API文档</a></h3> <hr /> <form asp-controller="WeChatPay" asp-action="UnifiedOrder" target="_blank"> <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>body:</label> <input type="text" class="form-control" name="body" value="微信扫码支付测试详情"> </div> <div class="form-group"> <label>total_fee:</label> <input type="text" class="form-control" name="total_fee" value="1"> </div> <div class="form-group"> <label>spbill_create_ip:</label> <input type="text" class="form-control" name="spbill_create_ip" value="127.0.0.1"> </div> <div class="form-group"> <label>notify_url(通知Url需外网环境可访问):</label> <input type="text" class="form-control" name="notify_url" value="http://xxx.com/wechatpay/notify"> </div> <div class="form-group"> <label>trade_type:</label> <input type="text" class="form-control" name="trade_type" value="NATIVE"> </div> <div class="form-group"> <label>product_id:</label> <input type="text" class="form-control" name="product_id" value="@DateTime.Now.ToString("yyyyMMddHHmmssfff")"> </div> <button type="submit" class="btn btn-primary">提交</button> </form></div>实现页面如下:
有疑问可以在 https://github.com/Essensoft/Payment 提交Issue ,也可以加入Payment 交流群:522457525本篇文章到此结束,具体效果可自行测试。感谢各位观看。原文地址:http://www.cnblogs.com/essenroc/p/8630730.html.NET社区新闻,深度好文,欢迎访问公众号文章汇总 http://www.csharpkit.com
相关文章推荐
- Asp.Net Core WebApi中接入Swagger组件(初级)
- ASP.NET Core Web API 最小化项目
- 使用Visual Studio Code开发Asp.Net Core WebApi学习笔记(二)-- Web Api Demo
- 用ASP.NET Core 1.0中实现邮件发送功能-阿里云邮件推送篇
- 浅谈ASP.Net Core WebApi几种版本控制对比
- asp.net core web app build success but fail to start up
- WebSocket in ASP.NET Core
- asp.net web 打印功能
- 问题:调用 ASP.Net Core WebAPI的HTTP POST方法时,从 [FromBody] 中读取的 MongoDB GeoJsonObjectModel成员总是null
- ASP.NET Core WebApi使用Swagger生成api说明文档看这篇就够了
- ASP.NET Core WebAPI 开发-新建WebAPI项目 转
- 用Middleware给ASP.NET Core Web API添加自己的授权验证
- ASP.NET Core 中文文档 第三章 原理(16).NET开放Web接口(OWIN)
- asp.net 2.0中新增的web.config的默认namespace功能
- ASP.NET Core Web 资源打包与压缩
- ASP.NET Core Web服务器 Kestrel和Http.sys 特性详解
- ASP.NET 添加 AJAX 和客户端功能_第一篇_将客户端脚本添加到 ASP.NET Web 应用程序中
- 在ASP.NET Core Web API上使用Swagger提供API文档
- asp.net paypal信用卡支付功能
- IT咨询顾问:一次吐血的项目救火 java或判断优化小技巧 asp.net core Session的测试使用心得 【.NET架构】BIM软件架构02:Web管控平台后台架构 NetCore入门篇:(十一)NetCore项目读取配置文件appsettings.json 使用LINQ生成Where的SQL语句 js_jquery_创建cookie有效期问题_时区问题