/// <summary> /// 微信支付统一下单,订单失效时间是1小时10分钟 /// </summary> /// <param name="request"></param> /// <returns></returns> private async Task <UnifiedorderResult> UnifiedOrderAsync(UnifiedOrderRequestDto request) { TenPayV3UnifiedorderRequestData data = new TenPayV3UnifiedorderRequestData(request.AppId, request.MerchantId, request.Body, request.OutTradeNo, request.TotalFee, "", request.NotifyUrl, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, request.OpenId, request.MerchantSecret, request.NonceStr, "WEB", DateTime.Now, DateTime.Now.AddHours(1).AddMinutes(10)); data.SignType = "MD5"; return(await TenPayV3.UnifiedorderAsync(data)); }
/// <summary> /// 统一下单 /// </summary> /// <param name="order_no">order_no</param> /// <returns></returns> public async Task <UnifiedorderResult> UnifiedorderAsync(string outTradeNo, string nonceStr, GetWeiXinPaymentBeforeRequestDto requestDto) { TenPayV3UnifiedorderRequestData data = new TenPayV3UnifiedorderRequestData(AppID, MerchantNumber, "医疗用品", outTradeNo, 1, "", "http://api-test.ghysjt.com/api/v1/mallpay/MallWeiXinPay/PaymentBackFunction", Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, requestDto.openId, MerchantSecret, nonceStr, "WEB", DateTime.Now, DateTime.Now.AddHours(1), "商品列表", "国丹医疗", "CNY", null, null, false); data.SignType = "MD5"; return(await TenPayV3.UnifiedorderAsync(data)); }
/// <summary> /// 二维码支付 /// </summary> /// <param name="appId"></param> /// <param name="mchId"></param> /// <param name="mchKey"></param> /// <param name="title"></param> /// <param name="totalAmount"></param> /// <param name="attach"></param> /// <param name="orderId"></param> /// <param name="localTradeNo"></param> /// <param name="notifyUrl"></param> /// <param name="expire"></param> /// <returns></returns> public async Task <PrePayResult <QrCodeResult> > BuildWxPayQrCode(string appId, string mchId, string mchKey, string title, int totalAmount, string attach, string orderId, string localTradeNo, string notifyUrl, TimeSpan?expire = null) { if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentException("支付标题不能为空", nameof(title)); } if (string.IsNullOrWhiteSpace(orderId)) { throw new ArgumentException("订单id不能为空", nameof(orderId)); } if (totalAmount < 1) { throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount)); } string nonceStr = TenPayV3Util.GetNoncestr(); // 微信支付统一订单 api调用,生成预付单 var requestData = new TenPayV3UnifiedorderRequestData( appId, mchId, title, localTradeNo, totalAmount, null, notifyUrl, TenPayV3Type.NATIVE, null, mchKey, nonceStr, attach: attach, productId: orderId, timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1)) ); var result = await TenPayV3.UnifiedorderAsync(requestData); Logger.LogInformation($"NATIVE支付预付单结果:{result.ResultXml}"); if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess()) { throw new Exception( $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}"); } return(new PrePayResult <QrCodeResult> { Result = new QrCodeResult { QrcodeUrl = result.code_url }, LocalTradeNo = localTradeNo, UnifiedorderResult = result }); }
/// <summary> /// 生成APP支付订单信息 /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <ResultDto> GetPayInfo(GetPayInfoInput input) { var requestHandler = new RequestHandler(); //微信开放平台审核通过的应用APPID requestHandler.SetParameter("appid", _tenPayV3Info.AppId); //微信支付分配的商户号 requestHandler.SetParameter("mch_id", _tenPayV3Info.MchId); //终端设备号(门店号或收银设备ID),默认请传"WEB" requestHandler.SetParameter("device_info", "WEB"); //随机字符串,不长于32位。推荐随机数生成算法 requestHandler.SetParameter("nonce_str", TenPayV3Util.GetNoncestr()); //签名,详见签名生成算法 //requestHandler.SetParameter("sign", ""); //签名类型,目前支持HMAC-SHA256和MD5,默认为MD5 //requestHandler.SetParameter("sign_type", "MD5"); //商品描述交易字段格式根据不同的应用场景按照以下格式:APP——需传入应用市场上的APP名字 - 实际商品名称,天天爱消除 - 游戏充值。 requestHandler.SetParameter("body", "报名费用。"); //商品详细列表,使用Json格式,传输签名前请务必使用CDATA标签将JSON文本串保护起来。goods_detail 服务商必填[]:└ goods_id String 必填 32 商品的编号└ wxpay_goods_id String 可选 32 微信支付定义的统一商品编号└ goods_name String 必填 256 商品名称└ quantity Int 必填 商品数量└ price Int 必填 商品单价,单位为分└ goods_category String 可选 32 商品类目ID└ body String 可选 1000 商品描述信息 //requestHandler.SetParameter("detail", json); //附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据 requestHandler.SetParameter("attach", ""); //商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一。详见商户订单号 requestHandler.SetParameter("out_trade_no", "123456"); //符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型 //requestHandler.SetParameter("fee_type", "CNY"); //订单总金额,单位为分,详见支付金额 requestHandler.SetParameter("total_fee", "100"); //用户端实际ip if (string.IsNullOrWhiteSpace(input.SpbillCreateIp)) { requestHandler.SetParameter("spbill_create_ip", HostAddressHelper.GetHostAddress()); } else { requestHandler.SetParameter("spbill_create_ip", input.SpbillCreateIp); } //订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则 requestHandler.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); //订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则 注意:最短失效时间间隔必须大于5分钟 requestHandler.SetParameter("time_expire", DateTime.Now.AddMinutes(15).ToString("yyyyMMddHHmmss")); //订单优惠标记,代金券或立减优惠功能的参数,说明详见代金券或立减优惠 //requestHandler.SetParameter("goods_tag", "WXG"); //接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。 requestHandler.SetParameter("notify_url", _tenPayV3Info.TenPayV3Notify); Logger.Debug("WeChatPay-GetPayInfo-notify_url-" + _tenPayV3Info.TenPayV3Notify); //支付类型 requestHandler.SetParameter("trade_type", "APP"); //no_credit--指定不能使用信用卡支付 //requestHandler.SetParameter("limit_pay", "no_credit"); //设置KEY requestHandler.SetKey(_tenPayV3Info.Key); var sign = requestHandler.CreateMd5Sign(); string data = requestHandler.ParseXML(sign); requestHandler.GetDebugInfo(); Logger.Debug("WeChatPay-GetPayInfo-xml-" + data); var result = await TenPayV3.UnifiedorderAsync(data); var tenPayV3Result = XmlHelper.WxXmlToObject <TenPayV3Result>(result); if (tenPayV3Result.return_code == "SUCCESS") { var unifiedorderResult = XmlHelper.WxXmlToObject <UnifiedorderResult>(result); var tenPayV3App = new TenPayV3App(); tenPayV3App.appid = unifiedorderResult.appid; tenPayV3App.partnerid = unifiedorderResult.mch_id; tenPayV3App.prepayid = unifiedorderResult.prepay_id; tenPayV3App.package = "Sign=WXPay"; tenPayV3App.packageValue = "Sign=WXPay"; tenPayV3App.noncestr = TenPayV3Util.GetNoncestr(); tenPayV3App.timestamp = TenPayV3Util.GetTimestamp(); var handler = new RequestHandler(); handler.SetParameter("appid", tenPayV3App.appid); handler.SetParameter("partnerid", tenPayV3App.partnerid); handler.SetParameter("prepayid", tenPayV3App.prepayid); handler.SetParameter("package", tenPayV3App.package); handler.SetParameter("noncestr", tenPayV3App.noncestr); handler.SetParameter("timestamp", tenPayV3App.timestamp); handler.SetKey(_tenPayV3Info.Key); tenPayV3App.sign = handler.CreateMd5Sign(); return(new ResultDto { Code = 0, Message = "生成APP支付订单信息", Data = tenPayV3App }); } return(new ResultDto { Code = 10, Message = tenPayV3Result.return_msg }); }
public async Task <IActionResult> Unifiedorder(UnifiedorderModel unifiedorder) { string appid = TenPyConfigRead.AppId; string scret = TenPyConfigRead.AppSecret; DateTimeOffset?timestart = null; DateTime? timeexpire = null; string feetype = "CNY"; // var result = await WxLogin.SendCodeForOpenId(appid, scret, code); // WxLoginModel loginModel= JsonSerializer.Deserialize<WxLoginModel>(result); if (string.IsNullOrWhiteSpace(unifiedorder.NotifyUrl)) { unifiedorder.NotifyUrl = TenPyConfigRead.TenPayV3_WxOpenNotify; } if (string.IsNullOrWhiteSpace(unifiedorder.NonceStr)) { unifiedorder.NonceStr = TenPayV3Util.GetNoncestr(); } if (!string.IsNullOrWhiteSpace(unifiedorder.TimeStart)) { timestart = DateTimeOffset.Parse(unifiedorder.TimeStart); } if (!string.IsNullOrWhiteSpace(unifiedorder.TimeExpire)) { timeexpire = DateTime.Parse(unifiedorder.TimeExpire); } if (!string.IsNullOrWhiteSpace(unifiedorder.FeeType)) { feetype = unifiedorder.FeeType; } var xmlDataInfo = new TenPayV3UnifiedorderRequestData(appId: TenPyConfigRead.AppId, mchId: TenPyConfigRead.MchId, body: unifiedorder.Body, outTradeNo: unifiedorder.OutTradeNo, totalFee: unifiedorder.TotalFee, spbillCreateIp: unifiedorder.SpbillCreateIP, notifyUrl: unifiedorder.NotifyUrl, tradeType: TenPayV3Type.JSAPI, openid: unifiedorder.OpenId, key: TenPyConfigRead.Key, nonceStr: unifiedorder.NonceStr, deviceInfo: unifiedorder.DeviceInfo, timeStart: timestart, timeExpire: timeexpire, detail: unifiedorder.Detail, attach: unifiedorder.Attach, feeType: feetype, goodsTag: unifiedorder.GoodsTag, productId: unifiedorder.ProductId, limitPay: unifiedorder.LimitPay); var result = await TenPayV3.UnifiedorderAsync(xmlDataInfo);//调用统一订单接口 var log = _logger.CreateLogger("统一下单"); if (result.return_code == "FAIL") { log.LogError($"商家订单号(OutTradeNo):{unifiedorder.OutTradeNo} 通讯标记(return_code):{result.return_code} {result.return_msg}"); } if (result.result_code == "FAIL") { log.LogError($"商家订单号(OutTradeNo):{unifiedorder.OutTradeNo} 业务结果(result_code):{result.result_code}\n{result.err_code}:{result.err_code_des}"); } else if (result.result_code == "SUCCESS") { log.LogInformation($"商家订单号(OutTradeNo):{unifiedorder.OutTradeNo} 业务结果(result_code):{result.result_code}"); } var timeStamp = TenPayV3Util.GetTimestamp(); var package = string.Format("prepay_id={0}", result.prepay_id); var paysign = TenPayV3.GetJsPaySign(TenPyConfigRead.AppId, timeStamp, unifiedorder.NonceStr, package, TenPyConfigRead.Key); // return Ok(new { timeStamp, nonceStr, package, paysign }); return(Ok(new { client = new { timeStamp, unifiedorder.NonceStr, package, paysign, sign = "MD5" }, respond = result, request = unifiedorder })); }
/// <summary> /// H5支付预付单 /// </summary> /// <param name="clientId">客户端ID</param> /// <param name="title">商品标题</param> /// <param name="totalAmount">支付金额(单位分)</param> /// <param name="attach">附加数据</param> /// <param name="orderId">订单id</param> /// <param name="openId">用户openid</param> /// <param name="clientIp">客户端ip(微信安全校验)</param> /// <param name="notifyUrl">支付完成通知地址,为空则使用配置中的</param> /// <param name="redirect_url">前端跳转地址</param> /// <returns></returns> public async Task <PrePayResult <H5PayResult> > BuildH5(string appId, string mchId, string mchKey, string title, int totalAmount, string attach, string orderId, string localTradeNo, string clientIp, string notifyUrl, string redirect_url, TimeSpan?expire = null) { if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentException("支付标题不能为空", nameof(title)); } if (string.IsNullOrWhiteSpace(orderId)) { throw new ArgumentException("订单id不能为空", nameof(orderId)); } if (totalAmount < 1) { throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount)); } string nonceStr = TenPayV3Util.GetNoncestr(); // 微信支付统一订单 api调用,生成预付单 var requestData = new TenPayV3UnifiedorderRequestData( appId, mchId, title, localTradeNo, totalAmount, clientIp, notifyUrl, TenPayV3Type.MWEB, null, mchKey, nonceStr, attach: attach, productId: orderId, timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1)) ); var result = await TenPayV3.UnifiedorderAsync(requestData); Logger.LogInformation($"MWEB支付预付单结果:{result.ResultXml}"); if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess()) { throw new Exception( $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}"); } string mWebUrl = result.mweb_url; if (redirect_url.IsNullOrWhiteSpace()) { if (!HttpUtility.UrlDecode(redirect_url).IsMatch(Consts.Regexs.Url)) { throw new ArgumentException("跳转参数错误", nameof(redirect_url)); } mWebUrl += string.Format("&redirect_url={0}", redirect_url); } return(new PrePayResult <H5PayResult> { Result = new H5PayResult { MwebUrl = mWebUrl }, LocalTradeNo = localTradeNo, UnifiedorderResult = result }); }
/// <summary> /// app支付预付单 /// </summary> /// <param name="clientId">客户端ID</param> /// <param name="title">商品标题</param> /// <param name="totalAmount">支付金额(单位分)</param> /// <param name="attach">附加数据</param> /// <param name="orderId">订单id</param> /// <param name="clientIp">客户端ip</param> /// <param name="notifyUrl">支付完成通知地址,为空则使用配置中的</param> /// <returns></returns> public async Task <PrePayResult <AppPayResult> > BuildApp(string appId, string mchId, string mchKey, string title, int totalAmount, string attach, string orderId, string localTradeNo, string clientIp, string notifyUrl, TimeSpan?expire = null) { if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentException("支付标题不能为空", nameof(title)); } if (string.IsNullOrWhiteSpace(orderId)) { throw new ArgumentException("订单id不能为空", nameof(orderId)); } if (totalAmount < 1) { throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount)); } string nonceStr = TenPayV3Util.GetNoncestr(); // 微信支付统一订单 api调用,生成预付单 var requestData = new TenPayV3UnifiedorderRequestData( appId, mchId, title, localTradeNo, totalAmount, clientIp, notifyUrl, TenPayV3Type.APP, null, mchKey, nonceStr, attach: attach, productId: orderId, timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1)) ); var result = await TenPayV3.UnifiedorderAsync(requestData); Logger.LogInformation($"APP支付预付单结果:{result.ResultXml}"); if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess()) { throw new Exception( $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}"); } var timeStamp = TenPayV3Util.GetTimestamp(); string nonceStrSign = TenPayV3Util.GetNoncestr(); ; var package = $"Sign=WXPay"; // 生成签名sign RequestHandler paySignReqHandler = new RequestHandler(null); paySignReqHandler.SetParameter("appid", appId); paySignReqHandler.SetParameter("timestamp", timeStamp); paySignReqHandler.SetParameter("noncestr", nonceStrSign); paySignReqHandler.SetParameter("package", package); paySignReqHandler.SetParameter("prepayid", result.prepay_id); paySignReqHandler.SetParameter("partnerid", mchId); var paySign = paySignReqHandler.CreateMd5Sign("key", mchKey); return(new PrePayResult <AppPayResult> { Result = new AppPayResult { Appid = appId, Noncestr = nonceStrSign, Prepayid = result.prepay_id, Package = package, Partnerid = mchId, Sign = paySign, Timestamp = timeStamp }, UnifiedorderResult = result, LocalTradeNo = localTradeNo }); }
/// <summary> /// 生成jsapi支付预付单(JASPI) /// </summary> /// <param name="clientId">客户端ID</param> /// <param name="title">商品标题</param> /// <param name="totalAmount">支付金额(单位分)</param> /// <param name="attach">附加数据</param> /// <param name="orderId">订单id</param> /// <param name="openId">用户openid</param> /// <param name="notifyUrl">支付完成通知地址,为空则使用配置中的</param> /// <returns></returns> public async Task <PrePayResult <JsApiResult> > BuildJsApi(string appId, string mchId, string mchKey, string title, int totalAmount, string attach, string orderId, string localTradeNo, string openId, string notifyUrl, TimeSpan?expire = null) { if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentException("支付标题不能为空", nameof(title)); } if (string.IsNullOrWhiteSpace(orderId)) { throw new ArgumentException("订单id不能为空", nameof(orderId)); } if (totalAmount < 1) { throw new ArgumentException("支付金额最低0.01元", nameof(totalAmount)); } string nonceStr = TenPayV3Util.GetNoncestr(); // 微信支付统一订单 api调用,生成预付单 var requestData = new TenPayV3UnifiedorderRequestData( appId, mchId, title, localTradeNo, totalAmount, null, notifyUrl, TenPayV3Type.JSAPI, openId, mchKey, nonceStr, attach: attach, productId: orderId, timeExpire: DateTime.Now.Add(expire ?? TimeSpan.FromHours(1)) ); var result = await TenPayV3.UnifiedorderAsync(requestData); Logger.LogInformation($"JASPI支付预付单结果:{result.ResultXml}"); if (!result.IsReturnCodeSuccess() || !result.IsResultCodeSuccess()) { throw new Exception( $"生成微信预付单失败,appid:{appId},request:{requestData.ToJson()},result:{result.ResultXml}"); } // 返回前端支付jaapi支付数据 var timeStamp = TenPayV3Util.GetTimestamp(); string nonceStrSign = TenPayV3Util.GetNoncestr(); var package = $"prepay_id={result.prepay_id}"; var sign = TenPayV3.GetJsPaySign(appId, timeStamp, nonceStrSign, package, mchKey); return(new PrePayResult <JsApiResult> { Result = new JsApiResult { AppId = appId, NonceStr = nonceStrSign, Package = package, PaySign = sign, SignType = "MD5", TimeStamp = timeStamp }, UnifiedorderResult = result, LocalTradeNo = localTradeNo }); }
public async Task <ApiResult <WeixinJsPaySignature> > Pay([FromBody] PayModelInput model, CancellationToken cancelToken) { /* * 接口根据订单id和小程序Code * 获取支付调起参数 */ if (string.IsNullOrWhiteSpace(model.Id)) { throw new NotImplementedException("订单Id信息为空!"); } //查询订单 var data = await _orderRepository.GetIncludeAsync(model.Id, cancelToken); ApiResult <WeixinJsPaySignature> apiResult = new ApiResult <WeixinJsPaySignature>(); _ = new ApiResult(); string timeStamp = TenPayV3Util.GetTimestamp(); AppLogger.Debug(JsonConvert.SerializeObject("1" + timeStamp), JsonConvert.SerializeObject(timeStamp)); string nonceStr = TenPayV3Util.GetNoncestr(); AppLogger.Debug(JsonConvert.SerializeObject("2" + nonceStr), JsonConvert.SerializeObject(nonceStr)); string PayV3_TenpayNotify = ConfigurationManager.AppSettings["PayV3_TenpayNotify"]; TenPayV3Info tenPayV3Info = new TenPayV3Info(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, PayV3_MchId, PayV3_Key, string.Empty, string.Empty, PayV3_TenpayNotify, string.Empty); AppLogger.Debug(JsonConvert.SerializeObject(tenPayV3Info), JsonConvert.SerializeObject(tenPayV3Info)); var openIdResult = SnsApi.JsCode2Json(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, model.Code); AppLogger.Debug(JsonConvert.SerializeObject(openIdResult), JsonConvert.SerializeObject(openIdResult)); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(tenPayV3Info.AppId, tenPayV3Info.MchId, "呙呙社区购物", data.Number, Convert.ToInt32(data.PaymentPrice * 100), GetClientIpAddress(Request), tenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openIdResult.openid, tenPayV3Info.Key, nonceStr, attach: data.Id.ToString()); AppLogger.Debug(DateTime.Now.ToString("yyyyMMddHHmmss") + "****TenPayV3UnifiedorderRequestData对象" + JsonConvert.SerializeObject(xmlDataInfo), "****TenPayV3UnifiedorderRequestData对象" + JsonConvert.SerializeObject(xmlDataInfo)); var resultPay = await TenPayV3.UnifiedorderAsync(xmlDataInfo); AppLogger.Debug("****TenPayV3.Unifiedorder返回对象" + JsonConvert.SerializeObject(resultPay), "****TenPayV3.Unifiedorder返回对象" + JsonConvert.SerializeObject(resultPay)); if (resultPay.return_code.ToUpper() == "SUCCESS") { if (resultPay.result_code.ToUpper() == "SUCCESS") { //设置支付参数 RequestHandler paySignReqHandler = new RequestHandler(null); paySignReqHandler.SetParameter("appId", tenPayV3Info.AppId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", resultPay.prepay_id)); paySignReqHandler.SetParameter("signType", "MD5"); paySignReqHandler.SetParameter("nonceStr", nonceStr); string paySign = paySignReqHandler.CreateMd5Sign("key", tenPayV3Info.Key); var jsmodel = new WeixinJsPaySignature { AppId = tenPayV3Info.AppId, Timestamp = timeStamp, NonceStr = nonceStr, Package = string.Format("prepay_id={0}", resultPay.prepay_id), PaySign = paySign, OrderId = data.Number, SignType = "MD5" }; apiResult.Data = jsmodel; return(apiResult); } else { } } else { throw new NotImplementedException(JsonConvert.SerializeObject(resultPay)); } return(apiResult); }