Exemplo n.º 1
0
        public async Task <JsonResult> GetPaySign(PayInput input)
        {
            using (CurrentUnitOfWork.DisableFilter(DataFilters.MustHaveTenant, DataFilters.MayHaveTenant))
            {
                Order        order        = _orderRepository.Get(input.Id);
                TenPayV3Info tenPayV3Info = await GetTenPayV3Info(InfrastructureSession.TenantId.Value);

                string timeStamp = TenPayV3Util.GetTimestamp();
                string nonceStr  = TenPayV3Util.GetNoncestr();

                if (order.PrepayIdCreatedTime.HasValue && order.PrepayIdCreatedTime < DateTime.Now.AddHours(-2))
                {
                    throw new UserFriendlyException(L("TheOrderHasOverTime"));
                }

                if (string.IsNullOrEmpty(order.PrepayId))
                {
                    string body             = order.Title;                 //商品或支付单简要描述
                    string out_trade_no     = order.Number;                //商户系统内部的订单号,32个字符内,可包含字母,其他说明见商户订单号
                    int    totalFee         = (int)(order.PayMoney * 100); //订单总金额,只能是整数。
                    string spbill_create_ip = Request.UserHostAddress;     //APP和网页支付提交用户端IP,Native支付填调用微信支付API的机器IP

                    string openid = WechatUserManager.GetOpenid(order.User.ToUserIdentifier());
                    TenPayV3UnifiedorderRequestData xmlDataInfo = new TenPayV3UnifiedorderRequestData(
                        tenPayV3Info.AppId,
                        tenPayV3Info.MchId,
                        body,
                        out_trade_no,
                        totalFee,
                        Request.UserHostAddress,
                        tenPayV3Info.TenPayV3Notify,
                        //trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。必传,这里需要将去获取openid赋值上去
                        TenPayV3Type.JSAPI,
                        openid,
                        tenPayV3Info.Key,
                        nonceStr);

                    UnifiedorderResult unifiedorderResult = TenPayV3.Unifiedorder(xmlDataInfo, 10000);
                    string             prepay_id          = unifiedorderResult.prepay_id;
                    order.PrepayId            = prepay_id;
                    order.PrepayIdCreatedTime = DateTime.Now;
                    _orderRepository.Update(order);
                }
                nonceStr = TenPayV3Util.GetNoncestr();

                RequestHandler paysignReqHandler = new RequestHandler(null);
                paysignReqHandler.Init();

                //设置支付参数
                paysignReqHandler.SetParameter("appId", tenPayV3Info.AppId);
                paysignReqHandler.SetParameter("timeStamp", timeStamp);
                paysignReqHandler.SetParameter("nonceStr", nonceStr);
                string package = string.Format("prepay_id={0}", order.PrepayId);
                paysignReqHandler.SetParameter("package", package);

                string paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key);
                paysignReqHandler.SetParameter("paySign", paySign);
                return(Json(paysignReqHandler.GetAllParameters()));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 支付前调用方法
        /// </summary>
        /// <param name="requestDto"></param>
        /// <returns></returns>
        public async Task <GetWeiXinPaymentBeforeResponseDto> GetPaymentBeforeAsync(string userId, GetWeiXinPaymentBeforeRequestDto requestDto)
        {
            //商品订单
            string outTradeNo = $"GDSPDD_{GetRandomString(10, false, false, true, false, "")}{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            //交易流水
            string TransactionNumber = $"GDJYLS_{GetRandomString(10, false, false, true, false, "")}{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            //随机字符串
            string nonceStr = GetRandomString(16, false, true, true, false, string.Empty);

            TransactionFlowingModel model = new TransactionFlowingModel();

            model.Amount                 = 1;
            model.OrgGuid                = string.Empty;
            model.CreatedBy              = userId;
            model.LastUpdatedBy          = userId;
            model.TransactionFlowingGuid = Guid.NewGuid().ToString("N");
            model.OutTradeNo             = outTradeNo;
            model.TransactionNumber      = TransactionNumber;
            model.TransactionStatus      = "WaitForPayment";
            model.Channel                = "微信支付";

            UnifiedorderResult unifie = await UnifiedorderAsync(outTradeNo, nonceStr, requestDto);

            if (unifie.IsReturnCodeSuccess())
            {
                model.ChannelNumber = unifie.prepay_id;
                model.Insert();
                GetWeiXinPaymentBeforeResponseDto result = new GetWeiXinPaymentBeforeResponseDto
                {
                    appId     = this.AppID,
                    nonceStr  = nonceStr,
                    timeStamp = Convert.ToInt32(GetTimeSpan().TotalSeconds),
                    package   = $"prepay_id={unifie.prepay_id}"
                };
                string sign = TenPayV3.GetJsPaySign(result.appId, result.timeStamp.ToString(), result.nonceStr, result.package, MerchantSecret, "MD5");
                result.sign     = sign;
                result.signType = "MD5";
                return(result);
            }
            else
            {
            }
            return(null);
        }
Exemplo n.º 3
0
        private static readonly string NotifyUrl = WxPayConfig.NotifyUrl;  //异步回调地址
        /// <summary>
        /// 统一下单
        /// </summary>
        /// <param name="body"></param>
        /// <param name="detail"></param>
        /// <param name="totalFee"></param>
        /// <param name="outTradeNo"></param>
        /// <param name="spbillCreateIp"></param>
        /// <param name="attach"></param>
        /// <returns></returns>
        public static Hashtable UnifiedOrder(string body, string detail, string totalFee, string outTradeNo, string spbillCreateIp, string attach)
        {
            TenPayV3UnifiedorderRequestData tenPayData = new TenPayV3UnifiedorderRequestData(AppId, MchId, body, outTradeNo, (totalFee.ToDecimal() * 100).ToString("0").ToInt32(), spbillCreateIp, NotifyUrl, TenPayV3Type.APP, "", Key,
                                                                                             Guid.NewGuid().ToString().Replace("-", ""), "WEB", null, DateTime.Now.AddMinutes(30), detail, attach);
            UnifiedorderResult result = TenPayV3.Unifiedorder(tenPayData);

            RequestHandler requestHandler = new RequestHandler();

            requestHandler.SetParameter("appid", result.appid);
            requestHandler.SetParameter("partnerid", result.mch_id);
            requestHandler.SetParameter("prepayid", result.prepay_id);
            requestHandler.SetParameter("package", "Sign=WXPay");
            requestHandler.SetParameter("noncestr", result.nonce_str);
            requestHandler.SetParameter("timestamp", System.DateTimeHelper.ConvertDateTimeInt(DateTime.Now).ToString());
            requestHandler.SetParameter("sign", requestHandler.CreateMd5Sign("key", Key));

            Hashtable request = requestHandler.GetAllParameters();

            return(request);
        }
#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释
        public WeChatUnifiedorderResult Pay(WeChatUnifiedorderParamter paramter)
#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释
        {
            string nonceStr  = GetNonceStr(paramter);
            string timeStamp = TenPayV3Util.GetTimestamp();

            TenPayV3UnifiedorderRequestData tenPayV3UnifiedorderRequestData = new TenPayV3UnifiedorderRequestData(
                Options.WeChatBaseOptions.AppId, Options.WeChatBaseOptions.MchId, paramter.Body, paramter.OutTradeNo, paramter.TotalFee, Options.WeChatBaseOptions.UserHostAddress,
                GetNotifyUrl(Options.WeChatBaseOptions.PayNotifyUrl, WeChatNotifyType.Pay), paramter.TradeType, paramter.OpenId, Options.WeChatBaseOptions.Key,
                nonceStr, paramter.DeviceInfo, paramter.TimeStart, paramter.TimeExpire, GetDetail(paramter), paramter.Attach,
                paramter.FeeType, paramter.GoodsTag, paramter.ProductId, paramter.LimitPay, GetSceneInfo(paramter), paramter.ProfitSharing);

            UnifiedorderResult unfortifiedResult = TenPayV3.Unifiedorder(tenPayV3UnifiedorderRequestData);

            if (unfortifiedResult.return_code != Model.ReturnCode.SUCCESS)
            {
                throw new WeChatServiceException($"微信统一下单失败, return_code: {unfortifiedResult.return_code}, return_msg: {unfortifiedResult.return_msg}.",
                                                 unfortifiedResult, typeof(UnifiedorderResult));
            }

            string package = $"prepay_id={unfortifiedResult.prepay_id}";

            return(new WeChatUnifiedorderResult
            {
                ResultXml = unfortifiedResult.ResultXml,
                DeviceInfo = unfortifiedResult.device_info,
                TradeType = unfortifiedResult.trade_type,
                MWebUrl = unfortifiedResult.mweb_url,
                PrepayId = unfortifiedResult.prepay_id,

                TimeStamp = timeStamp,
                NonceStr = nonceStr,
                Package = package,
                CodeUrl = unfortifiedResult.code_url,
                JsPaySign = TenPayV3.GetJsPaySign(Options.WeChatBaseOptions.AppId, timeStamp, nonceStr, package, Options.WeChatBaseOptions.Key)
            });
        }
Exemplo n.º 5
0
        /// <summary>
        ///     <see cref="https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1" />
        ///     除付款码支付场景以外,商户系统先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易会话标识后再按不同场景生成交易串调起支付。
        /// </summary>
        /// <param name="appId">服务商商户的 AppId。</param>
        /// <param name="mchId">微信支付分配的商户号。</param>
        /// <param name="key">服务商商户的 key。</param>
        /// <param name="subAppId">微信分配的子商户公众账号 Id。<br />如需在支付完成后获取 <paramref name="subOpenId" /> 则此参数必传。</param>
        /// <param name="subMchId">微信支付分配的子商户号。</param>
        /// <param name="deviceInfo">终端设备号 (门店号或收银设备 Id),注意:PC 网页或 JSAPI 支付请传 "WEB"。</param>
        /// <param name="receipt">传入 Y 时,支付成功消息和支付详情页将出现开票入口。需要在微信支付商户平台或微信公众平台开通电子发票功能,传此字段才可生效。</param>
        /// <param name="body">具体的商品描述信息,建议根据不同的场景传递不同的描述信息。</param>
        /// <param name="detail">商品详细描述,对于使用单品优惠的商户,该字段必须按照规范上传。</param>
        /// <param name="attach">附加数据,在查询 API 和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据。</param>
        /// <param name="outTradeNo">商户系统内部订单号,要求 32 个字符内,只能是数字、大小写字母_-|* 且在同一个商户号下唯一。</param>
        /// <param name="feeType">符合 ISO 4217 标准的三位字母代码,默认人民币:CNY。</param>
        /// <param name="totalFee">订单总金额,只能为整数,单位是分。</param>
        /// <param name="billCreateIp">调用微信支付 API 的机器 IP,可以使用 IPv4 或 IPv6。</param>
        /// <param name="timeStart">订单生成时间,格式为 yyyyMMddHHmmss。</param>
        /// <param name="timeExpire">订单失效时间,格式为 yyyyMMddHHmmss。</param>
        /// <param name="goodsTag">订单优惠标记,代金券或立减优惠功能的参数。</param>
        /// <param name="notifyUrl">接收微信支付异步通知回调地址,通知 Url 必须为直接可访问的 Url,不能携带参数。</param>
        /// <param name="tradeType">交易类型,请参考 <see cref="Consts.TradeType" /> 的定义。</param>
        /// <param name="productId">当 <paramref name="tradeType" /> 参数为 <see cref="Consts.TradeType.Native" /> 时,此参数必填。</param>
        /// <param name="limitPay">指定支付方式,传递 no_credit 则说明不能使用信用卡支付。</param>
        /// <param name="openId">当 <paramref name="tradeType" /> 参数为 <see cref="Consts.TradeType.JsApi" /> 时,此参数必填。如果选择传 <paramref name="subOpenId" />, 则必须传 <paramref name="subAppId" />。</param>
        /// <param name="subOpenId">当 <paramref name="tradeType" /> 参数为 <see cref="Consts.TradeType.JsApi" /> 时,此参数必填。如果选择传 <paramref name="subOpenId" />, 则必须传 <paramref name="subAppId" />。</param>
        /// <param name="sceneInfo">该字段常用于线下活动时的场景信息上报,支持上报实际门店信息,商户也可以按需求自己上报相关信息。</param>
        public async Task <UnifiedorderResult> UnifiedOrderAsync(
            string appId,
            string mchId,
            string mchKey,
            string body, string outTradeNo, int totalFee, string notifyUrl, string tradeType,
            string openId       = "",
            string billCreateIp = "",
            string subAppId     = "",
            string subMchId     = "",
            string deviceInfo   = "", string receipt    = "",
            string detail       = "", string attach     = "", string feeType  = "",
            string timeStart    = "", string timeExpire = "", string goodsTag = "",
            string productId    = "",
            string limitPay     = "", string subOpenId = "", string sceneInfo = "")
        {
            if (tradeType == Consts.TradeType.JsApi && string.IsNullOrEmpty(openId))
            {
                throw new ArgumentException($"当交易类型为 JsApi 时,参数 {nameof(openId)} 必须传递有效值。");
            }

            if (!string.IsNullOrEmpty(subOpenId) && string.IsNullOrEmpty(subAppId))
            {
                throw new ArgumentException($"传递子商户的 OpenId 时,参数 {nameof(subAppId)} 必须传递有效值。");
            }

            var request = new PayParameters();

            request.AddParameter("appid", appId);
            request.AddParameter("mch_id", mchId);
            request.AddParameter("sub_appid", subAppId);
            request.AddParameter("sub_mch_id", subMchId);
            request.AddParameter("device_info", deviceInfo);
            request.AddParameter("nonce_str", RandomExt.GetRandom());


            request.AddParameter("sign_type", "MD5");
            request.AddParameter("body", body);
            request.AddParameter("detail", detail);
            request.AddParameter("attach", attach);
            request.AddParameter("out_trade_no", outTradeNo);
            request.AddParameter("fee_type", feeType);
            request.AddParameter("total_fee", totalFee);
            request.AddParameter("spbill_create_ip", billCreateIp);
            request.AddParameter("time_start", timeStart);
            request.AddParameter("time_expire", timeExpire);
            request.AddParameter("goods_tag", goodsTag);
            request.AddParameter("notify_url", notifyUrl);
            request.AddParameter("trade_type", tradeType);
            request.AddParameter("product_id", productId);
            request.AddParameter("limit_pay", limitPay);
            request.AddParameter("openid", openId);
            request.AddParameter("receipt", receipt);
            request.AddParameter("scene_info", sceneInfo);
            request.AddParameter("sub_openid", subOpenId);
            //request.AddParameter("key", mchKey);

            var signStr = _signatureGenerator.Generate(request, MD5.Create(), mchKey);

            request.AddParameter("sign", signStr);

            var xmlResult = await RequestAndGetReturnValueAsync("pay/unifiedorder", request);

            var result = new UnifiedorderResult(xmlResult);

            var package = $"prepay_id={result.prepay_id}";

            result.PaySign = _signatureGenerator.GetJsPaySign(
                subAppId.IsNullOrEmptyOrWhiteSpace() ? appId : subAppId, //如果是服务商模式,这里是SubAppId
                result.TimeStamp,
                result.nonce_str,
                package, mchKey);

            return(result);
        }
Exemplo n.º 6
0
        public async Task <ActionResult> Index(FormCollection collection)
        {
            ModelForOrder order        = null;
            int           totalfee     = 0;
            object        objResult    = "";
            string        strTotal_fee = Request.Form["totalfee"];

            if (int.TryParse(strTotal_fee, out totalfee))
            {
                totalfee = totalfee * 100;
                OAuthAccessTokenResult tokenResult = Session["AccessToken"] as OAuthAccessTokenResult;
                string body           = "瑞雪管理系统充值";
                string timeStamp      = TenPayV3Util.GetTimestamp();
                string nonceStr       = TenPayV3Util.GetNoncestr();
                string openid         = tokenResult.openid;
                string tenPayV3Notify = "http://w.roccode.cn/pay/ResultNotify";
                string key            = "8f75e82b6f1b7d82f7952121a6801b4a";
                string billNo         = string.Format("{0}{1}{2}", WeixinData.MchId, DateTime.Now.ToString("yyyyMMddHHmmss"), TenPayV3Util.BuildRandomStr(6));
                var    xmlDataInfo    = new TenPayV3UnifiedorderRequestData(WeixinData.AppId, WeixinData.MchId, body, billNo, totalfee, Request.UserHostAddress,
                                                                            tenPayV3Notify, Senparc.Weixin.MP.TenPayV3Type.JSAPI, openid, key, nonceStr);

                UnifiedorderResult result = TenPayV3.Unifiedorder(xmlDataInfo);        //调用统一订单接口

                if (result.result_code == "SUCCESS")
                {
                    order              = new ModelForOrder();
                    order.appId        = result.appid;
                    order.nonceStr     = result.nonce_str;
                    order.packageValue = "prepay_id=" + result.prepay_id;
                    order.paySign      = TenPayV3.GetJsPaySign(result.appid, timeStamp, result.nonce_str, order.packageValue, key);
                    order.timeStamp    = timeStamp;
                    order.msg          = "预支付订单生成成功";

                    // 保存预支付订单信息
                    string id = Session["readerId"] as string;
                    //OAuthUserInfo userInfo = Session["UserInfo"] as OAuthUserInfo;
                    if (!string.IsNullOrEmpty(id))
                    {
                        string groundCode = id.Substring(0, 6);
                        string gameCode   = id.Substring(6, 2);
                        string readerCode = id.Substring(8, 3);
                        //string sn = id.Substring(11, 5);
                        db.Orders.Add(new Order()
                        {
                            GroundCode = groundCode,
                            GameCode   = gameCode,
                            ReaderCode = readerCode,
                            Amt        = totalfee / 100,
                            BillNo     = billNo,
                            //WeiXinCode = userInfo.nickname,
                            //Openid = userInfo.openid,
                            //Unionid = userInfo.unionid
                        });
                        db.SaveChanges();
                    }
                }
            }
            else
            {
                order     = new ModelForOrder();
                order.msg = "输入充值数量异常";
            }
            if (order == null)
            {
                order     = new ModelForOrder();
                order.msg = "预支付订单生成失败,请重试!";
            }
            objResult = order;
            return(Json(objResult));
        }
Exemplo n.º 7
0
        public ComplexResponse <object> PayOrder(string tradeNo, string token)
        {
            try
            {
                var    msg  = Enums.PayErrorMsg.失败;
                object data = null;

                if (!string.IsNullOrEmpty(tradeNo))
                {
                    // 校验 token(3rd_session)是否过期
                    var flag = _userService.CheckToken(token);
                    if (flag)
                    {
                        // 查取订单数据(实付费用、openId)
                        var payOrderInfo = _orderService.GetPayOrderInfoByTradeNo(tradeNo);

                        if (!string.IsNullOrEmpty(payOrderInfo.TradeNo) && !string.IsNullOrEmpty(payOrderInfo.OpenId))
                        {
                            // 调起支付接口
                            var test           = ConfigurationManager.AppSettings["test"];
                            var appId          = ConfigurationManager.AppSettings["appId"];
                            var mchId          = ConfigurationManager.AppSettings["mchId"];
                            var body           = ConfigurationManager.AppSettings["siteName"];
                            var totalFee       = (!string.IsNullOrEmpty(test) && test.Equals("true")) ? 1 : payOrderInfo.TotalFee;
                            var spbillCreateIp = HttpContext.Current.Request.UserHostAddress;
                            var notifyUrl      = ConfigurationManager.AppSettings["notifyUrl"] ??
                                                 "https://wxapi.xzpfood.com/api/pay/notify";
                            var openId = payOrderInfo.OpenId;
                            var key    = ConfigurationManager.AppSettings["appKey"];

                            var requestData = new TenPayV3UnifiedorderRequestData(appId, mchId, body, tradeNo, totalFee,
                                                                                  spbillCreateIp, notifyUrl, TenPayV3Type.JSAPI, openId, key, TenPayV3Util.GetNoncestr());
                            UnifiedorderResult result = TenPayV3.Unifiedorder(requestData);

                            LogHelper.Info("\n\n统一下单结果:\n" + JsonHelper.Serialize(result));

                            if (result.IsResultCodeSuccess())
                            {
                                string package   = "prepay_id=" + result.prepay_id;
                                string timeStamp = TenPayV3Util.GetTimestamp();
                                string nonceStr  = TenPayV3Util.GetNoncestr();
                                string paySign   = TenPayV3.GetJsPaySign(appId, timeStamp, nonceStr, package, key);
                                string signType  = "MD5";
                                data = new { timeStamp, nonceStr, package, paySign, signType };

                                msg = Enums.PayErrorMsg.成功;
                            }
                        }
                    }
                    else
                    {
                        msg = Enums.PayErrorMsg.用户登录信息过期;
                    }
                }
                else
                {
                    msg = Enums.PayErrorMsg.参数错误;
                }

                return(new ComplexResponse <dynamic>((int)msg, msg.ToString(), data));
            }
            catch (Exception ex)
            {
                LogHelper.Debug("\n\n支付异常:\n", ex);
                return(new ComplexResponse <object>((int)Enums.PayErrorMsg.失败, ex.ToString()));
            }
        }