.NET Core之微信支付之公众号、H5支付详解
前言
本篇主要记录微信支付中公众号及h5支付全过程。
准备篇
公众号或者服务号(并开通微信支付功能)、商户平台中开通jsapi支付、h5支付。
配置篇
公众号或者服务号中 -------开发-------开发者工具---------web开发者工具-------绑定为开发者
公众号或者服务号中 -------公众号设置--------功能设置 :填写业务域名、js安全域名、网页授权域名 示例:pay.one.com
商户平台中--------产品中心-------开发配置------jsapi支付授权目录填写:http://pay.one.com/ http://pay.one.com/wechatpay/pubpay/-----h5支付填写:pay.one.com
若对配置还有疑问,可参考官方文档:
开发篇
jsapi支付
本demo是基于payment 的sdk开发。具体详情可参考: https://github.com/essensoft/payment
首先 使用nuget安装payment:
install-package :essensoft.aspnetcore.payment.wechatpay -version 2.3.2
建一个model: wechatpaypubpayviewmodel
public class wechatpaypubpayviewmodel { [required] [display(name = "out_trade_no")] public string outtradeno { get; set; } [required] [display(name = "body")] public string body { get; set; } [required] [display(name = "total_fee")] public int totalfee { get; set; } [required] [display(name = "spbill_create_ip")] public string spbillcreateip { get; set; } [required] [display(name = "notify_url")] public string notifyurl { get; set; } [required] [display(name = "trade_type")] public string tradetype { get; set; } [required] [display(name = "openid")] public string openid { get; set; } }
wechatpaycontroller:
//微信支付请求客户端(用于处理请求与响应) private readonly iwechatpayclient _client; private readonly ilogger<wechatpaycontroller> _logger; private ihttpcontextaccessor _accessor; public wechatpaycontroller(iwechatpayclient client, ihttpcontextaccessor accessor, ilogger<wechatpaycontroller> logger) { _client = client; _accessor = accessor; _logger = logger; } /// <summary> /// 公众号支付 /// </summary> /// <returns></returns> [httpget] public iactionresult pubpay() { wechatpaypubpayviewmodel paymodel=new wechatpaypubpayviewmodel() { body = "微信公众号支付测试", outtradeno = datetime.now.tostring("yyyymmddhhmmssfff"), totalfee = 1,//分 单位 spbillcreateip = "127.0.0.1", notifyurl = "http://pay.one.com/notify/wechatpay/unifiedorder", tradetype = "jsapi", openid = "" //此处需进行授权 获取openid }; return view(paymodel); } /// <summary> /// 公众号支付 /// </summary> /// <param name="viewmodel"></param> /// <returns></returns> [httppost] public async task<iactionresult> pubpay(wechatpaypubpayviewmodel viewmodel) { if(string.isnullorempty(viewmodel.openid)) { viewdata["response"] = "请返回上级重新进入此页面以获取最新数据"; return view(); } var request = new wechatpayunifiedorderrequest { body = viewmodel.body, outtradeno = viewmodel.outtradeno, totalfee = viewmodel.totalfee, spbillcreateip = viewmodel.spbillcreateip, notifyurl = viewmodel.notifyurl, tradetype = viewmodel.tradetype, openid = viewmodel.openid //此处需进行授权 获取openid }; var response = await _client.executeasync(request);if (response.returncode == "success" && response.resultcode == "success") { var req = new wechatpayh5callpaymentrequest { package = "prepay_id=" + response.prepayid }; var parameter = await _client.executeasync(req); // 将参数(parameter)给 公众号前端 让他在微信内h5调起支付(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6) viewdata["parameter"] = jsonconvert.serializeobject(parameter); viewdata["response"] = response.body; return view(); } viewdata["response"] = response.body; return view(); }
注意:公众号或者微信内支付,需要授权获取到用户的openid。所以,此处我们还需要进行微信授权,而授权方式有两种,一种是静默授权、一种是需要用户同意,区别是 静默授权只能拿到openid,而经用户同意后可拿到 微信头像、昵称、性别等其他信息。
具体可参阅文档:
页面:
@using newtonsoft.json @model wechatpaypubpayviewmodel @{ viewdata["title"] = "公众号支付-统一下单"; } <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a asp-controller="wechatpay" asp-action="index">微信支付</a></li> <li class="breadcrumb-item active" aria-current="page">@viewdata["title"]</li> </ol> </nav> <br /> <div class="card"> <div class="card-body"> <form asp-controller="wechatpay" asp-action="pubpay"> <div asp-validation-summary="all" class="text-danger"></div> <div class="form-group"> <label asp-for="outtradeno"></label> <input type="text" class="form-control" asp-for="outtradeno" value="@model?.outtradeno" /> </div> <div class="form-group"> <label asp-for="body"></label> <input type="text" class="form-control" asp-for="body" value="@model?.body" /> </div> <div class="form-group"> <label asp-for="totalfee"></label> <input type="text" class="form-control" asp-for="totalfee" value="@model?.totalfee" /> </div> <div class="form-group"> <label asp-for="spbillcreateip"></label> <input type="text" class="form-control" asp-for="spbillcreateip" value="@model?.spbillcreateip" /> </div> <div class="form-group"> <label asp-for="notifyurl"></label> <input type="text" class="form-control" asp-for="notifyurl" value="@model?.notifyurl" /> </div> <div class="form-group"> <label asp-for="tradetype"></label> <input type="text" class="form-control" asp-for="tradetype" value="@model?.tradetype" /> </div> <div class="form-group"> <label asp-for="openid"></label> <input type="text" class="form-control" asp-for="openid" value="@model?.openid" /> </div> <button type="submit" class="btn btn-primary">提交请求</button> <button type="button" class="btn btn-success" id="paynow">立即支付</button> </form> <hr /> <form class="form-horizontal"> <div class="form-group"> <label>response:</label> <textarea class="form-control" rows="10">@viewdata["response"]</textarea> </div> <div class="form-group"> <label>parameter:</label> <textarea class="form-control" rows="3">@viewdata["parameter"]</textarea> </div> </form> </div> </div> @section scripts { @{await html.renderpartialasync("_validationscriptspartial"); } } <script src="~/lib/jquery/dist/jquery.min.js"></script> <script type="text/javascript"> $(function () { $("#paynow").on('click', function () { const local = "http://pay.one.com/wechatpay/payback/"; window.location.href ='https://open.weixin.qq.com/connect/oauth2/authorize?appid=@viewbaig.appid&redirect_uri=' + encodeuricomponent(local)+'&response_type=code&scope=snsapi_base&state=a#wechat_redirect'; }); }); </script>
此时:payback action如下:
[httpget] public async task<iactionresult> payback() { var code = request.query["code"]; var state = request.query["state"]; oauthtoken tokenmodel = new oauthtoken(); //通过code换取token if (!string.isnullorempty(code)) { _logger.logwarning("授权成功"); viewbag.code = code; tokenmodel = oauthapi.getauthtoken(code, wechatappid); } var request = new wechatpayunifiedorderrequest { body = "微信公众号支付测试", outtradeno = datetime.now.tostring("yyyymmddhhmmssfff"), totalfee = 1,//分 单位 spbillcreateip = "127.0.0.1", notifyurl = "http://pay.one.com/notify/wechatpay/unifiedorder", tradetype = "jsapi", openid = tokenmodel.openid //此处需进行授权 获取openid }; var response = await _client.executeasync(request); _logger.logwarning($"统一下单接口返回:{response.returncode}"); if (response.returncode == "success" && response.resultcode == "success") { var req = new wechatpayh5callpaymentrequest { package = "prepay_id=" + response.prepayid }; var parameter = await _client.executeasync(req); // 将参数(parameter)给 公众号前端 让他在微信内h5调起支付(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6) viewdata["parameter"] = jsonconvert.serializeobject(parameter); _logger.logwarning($"统一下单成功,即将调起微信支付:{viewdata["parameter"].tostring()}"); viewdata["response"] = response.body; return view(); } viewdata["response"] = response.body; return view(); }
其中:oauthtoken是网页授权 返回的实体:
/// 获取网页授权token时,返回的实体 /// </summary> public class oauthtoken : baseres { /// <summary> /// 网页授权接口调用凭证。注意:此access_token与基础支持的access_token不同 /// </summary> [jsonproperty("access_token")] public string accesstoken { get; set; } private int _expiresin; /// <summary> /// access_token接口调用凭证超时时间,单位(秒) /// </summary> [jsonproperty("expires_in")] public int expiresin { get { return _expiresin; } set { expirestime = datetime.now.addseconds(value); _expiresin = value; } } /// <summary> /// 用于刷新access_token /// </summary> [jsonproperty("refresh_token")] public string refreshtoken { get; set; } /// <summary> /// 用户唯一标识。请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的openid /// </summary> [jsonproperty("openid")] public string openid { get; set; } /// <summary> /// 用户授权的作用域,使用逗号(,)分隔 /// </summary> [jsonproperty("scope")] public string scope { get; set; } [jsonproperty("expires_time")] public datetime expirestime { get; set; } /// <summary> /// 只有在用户将公众号绑定到微信开放平台账号后,才会出现该字段 /// </summary> [jsonproperty("unionid")] public string unionid { get; set; } }
最后 贴一下支付成功后的回调函数:
[route("notify/wechatpay")] public class wechatpaynotifycontroller : controller { private readonly iwechatpaynotifyclient _client; private readonly ilogger<wechatpaynotifycontroller> _logger; public wechatpaynotifycontroller(iwechatpaynotifyclient client,ilogger<wechatpaynotifycontroller> logger) { _client = client; _logger = logger; } /// <summary> /// 统一下单支付结果通知 /// </summary> /// <returns></returns> [route("unifiedorder")] [httppost] public async task<iactionresult> unifiedorder() { try { _logger.logwarning($"进入回调"); var payconfig = openapi.getpayconfig(); var notify = await _client.executeasync<wechatpayunifiedordernotify>(request); _logger.logwarning($"返回状态码:{notify.returncode}"); if (notify.returncode == "success") { _logger.logwarning($"业务结果码:{notify.resultcode}"); if (notify.resultcode == "success") { _logger.logwarning($"支付方式:{notify.tradetype}"); _logger.logwarning($"商户订单号:{notify.outtradeno}"); _logger.logwarning($"微信支付订单号:{notify.transactionid}"); _logger.logwarning($"支付金额:{notify.totalfee}"); return wechatpaynotifyresult.success; } } return nocontent(); } catch(exception ex) { _logger.logwarning($"回调失败:{ex.message}"); return nocontent(); } } }
然后测试一下支付,查看服务器log如下:
h5支付
h5支付是指再除开微信浏览器以外的移动端浏览器上进行微信回复操作。
和上面步骤大体一致,有几个地方需要注意
1:客户端ip问题:h5支付的时候,微信支付系统会根据客户端调起的当前ip 作为支付ip,若发现 发起支付请求时,ip有问题,则会支付失败,或者提示系统繁忙。这里贴一下我获取ip的代码:
utils.getuserip(_accessor.httpcontext);//页面上调用 /// <summary> /// 穿过代理服务器获取真实ip /// </summary> /// <returns></returns> public static string getuserip(this httpcontext context) { var ip = context.request.headers["x-forwarded-for"].firstordefault(); if (string.isnullorempty(ip)) { ip = context.connection.remoteipaddress.tostring(); } return ip; }
2:tradetype类型应该是:mweb
3:若调起微信支付成功后,默认回调到支付首页,若需要设置回调页面,则可以再url中拼接:
/// <summary> /// h5支付 /// </summary> /// <param name="viewmodel"></param> /// <returns></returns> [httppost] public async task<iactionresult> h5pay(wechatpayh5payviewmodel viewmodel) { var request = new wechatpayunifiedorderrequest { body = viewmodel.body, outtradeno = viewmodel.outtradeno, totalfee = viewmodel.totalfee, spbillcreateip = viewmodel.spbillcreateip, notifyurl = viewmodel.notifyurl, tradetype = viewmodel.tradetype }; var response = await _client.executeasync(request); // mweb_url为拉起微信支付收银台的中间页面,可通过访问该url来拉起微信客户端,完成支付,mweb_url的有效期为5分钟。 if (response.mweburl == null) { viewdata["response"] = response.returnmsg; return view(); } return redirect(response.mweburl); }
更多详细可参考文档: https://pay.weixin.qq.com/wiki/doc/api/h5.php?chapter=15_4
4:支付结果通知:
注意:
1、同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。
2、后台通知交互时,如果微信收到商户的应答不符合规范或超时,微信会判定本次通知失败,重新发送通知,直到成功为止(在通知一直不成功的情况下,微信总共会发起10次通知,通知频率为15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h - 总计 24h4m),但微信不保证通知最终一定能成功。
3、在订单状态不明或者没有收到微信支付结果通知的情况下,建议商户主动调用微信支付【 查询订单api 】确认订单状态。
特别提醒:
1、商户系统对于支付结果通知的内容一定要做 签名验证,并校验返回的订单金额是否与商户侧的订单金额一致 ,防止数据泄漏导致出现“假通知”,造成资金损失。
2、当收到通知进行处理时,首先检查对应业务数据的状态,判断该通知是否已经处理过,如果没有处理过再进行处理,如果处理过直接返回结果成功。在对业务数据进行状态检查和处理之前,要采用数据锁进行并发控制,以避免函数重入造成的数据混乱。
最后可以测试下h5支付,查看返回的log:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。