예제 #1
0
        public ActionResult TestPay()
        {
            #region 统一下单

            LogManager.GetCurrentClassLogger().Debug("开始下单");
            var model = new UnifiedorderRequest {
                OpenId = WeiChatApplicationContext.Current.WeiChatUser.OpenId
            };
            LogManager.GetCurrentClassLogger().Debug(JsonConvert.SerializeObject(model.OpenId));
            model.SpbillCreateIp = "8.8.8.8";
            model.OutTradeNo     = PayUtil.GenerateOutTradeNo();
            model.TotalFee       = "1";
            model.NonceStr       = PayUtil.GetNoncestr();
            model.TradeType      = "JSAPI";
            model.Body           = "购买商品";
            model.DeviceInfo     = "WEB";
            var result = WeChatApisContext.Current.TenPayV3Api.Unifiedorder(model);

            var _dict = new Dictionary <string, string>
            {
                { "appId", result.AppId },
                { "timeStamp", PayUtil.GetTimestamp() },
                { "nonceStr", result.NonceStr },
                { "package", "prepay_id=" + result.PrepayId },
                { "signType", "MD5" }
            };
            _dict.Add("paySign", PayUtil.CreateMd5Sign(_dict, WeChatConfigManager.Current.GetPayConfig().TenPayKey));

            #endregion

            ViewBag.PayPam = JsonConvert.SerializeObject(_dict);
            return(View());
        }
예제 #2
0
        public IHttpActionResult WechatPay(Guid id)
        {
            try
            {
                //查询订单
                var order =
                    db.Order_Infos.SingleOrDefault(
                        o => (o.Id == id) && (o.OpenId == WeiChatApplicationContext.Current.WeiChatUser.OpenId));
                if (null == order)
                {
                    return(BadRequest("订单信息不存在"));
                }

                #region 统一下单
                var model = new UnifiedorderRequest
                {
                    OpenId         = WeiChatApplicationContext.Current.WeiChatUser.OpenId,
                    SpbillCreateIp = "8.8.8.8",
                    OutTradeNo     = order.Code,
                    TotalFee       = Convert.ToInt32((order.TotalPrice + order.Shipping) * 100).ToString(),
                    NonceStr       = PayUtil.GetNoncestr(),
                    TradeType      = "JSAPI",
                    Body           = "购买商品",
                    DeviceInfo     = "WEB"
                };
                var result = WeChatApisContext.Current.TenPayV3Api.Unifiedorder(model);

                var _dict = new Dictionary <string, string>
                {
                    { "appId", result.AppId },
                    { "timeStamp", PayUtil.GetTimestamp() },
                    { "nonceStr", result.NonceStr },
                    { "package", "prepay_id=" + result.PrepayId },
                    { "signType", "MD5" }
                };
                _dict.Add("paySign", PayUtil.CreateMd5Sign(_dict, WeChatConfigManager.Current.GetPayConfig().TenPayKey));

                #endregion

                return(Ok(_dict));
            }
            catch (Exception ex)
            {
                log.Log(LoggerLevels.Error, "WechatPay:" + ex.Message);
            }
            return(BadRequest("操作失败,请联系管理员!"));
        }
        public IHttpActionResult PayMoney([FromBody] Log_Recharge model)
        {
            log.Log(LoggerLevels.Debug, "进入API[PayMoney]");
            if (model.Amount <= 0)
            {
                return(BadRequest("充值金额必须大于0!"));
            }

            #region 统一下单

            var paymodel = new UnifiedorderRequest
            {
                OpenId         = WeiChatApplicationContext.Current.WeiChatUser.OpenId,
                SpbillCreateIp = "8.8.8.8",
                OutTradeNo     = PayUtil.GenerateOutTradeNo(),
                TotalFee       = Convert.ToInt32(model.Amount * 100).ToString(),
                NonceStr       = PayUtil.GetNoncestr(),
                TradeType      = "JSAPI",
                Body           = "购买商品",
                DeviceInfo     = "WEB"
            };
            var result = WeChatApisContext.Current.TenPayV3Api.Unifiedorder(paymodel);

            var _dict = new Dictionary <string, string>
            {
                { "appId", result.AppId },
                { "timeStamp", PayUtil.GetTimestamp() },
                { "nonceStr", result.NonceStr },
                { "package", string.Format("prepay_id={0}", result.PrepayId) },
                { "signType", "MD5" }
            };
            _dict.Add("paySign", PayUtil.CreateMd5Sign(_dict, WeChatConfigManager.Current.GetPayConfig().TenPayKey));

            #endregion

            return(Ok(_dict));
        }
예제 #4
0
        /// <summary>
        ///     小程序支付
        ///     小程序统一下单接口
        ///     https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1
        /// </summary>
        /// <returns></returns>
        public MiniProgramPayOutput MiniProgramPay(MiniProgramPayInput input)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            if (input.TotalFee <= 0)
            {
                throw new ArgumentException("金额不能小于0!", nameof(input.TotalFee));
            }

            if (string.IsNullOrWhiteSpace(input.OpenId))
            {
                throw new ArgumentNullException("OpenId必须填写!", nameof(input.OpenId));
            }

            if (string.IsNullOrWhiteSpace(input.Body))
            {
                throw new ArgumentNullException("商品描述必须填写!", nameof(input.Body));
            }

            if (string.IsNullOrWhiteSpace(input.SpbillCreateIp))
            {
                throw new ArgumentNullException("终端IP必须填写!", nameof(input.SpbillCreateIp));
            }

            var url    = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            var config = GetConfig();

            var model = new UnifiedorderRequest
            {
                AppId          = config.PayAppId,
                MchId          = config.MchId,
                Attach         = input.Attach,
                Body           = input.Body,
                Detail         = input.Detail,
                DeviceInfo     = input.DeviceInfo,
                FeeType        = input.FeeType,
                GoodsTag       = input.GoodsTag,
                LimitPay       = input.LimitPay,
                OpenId         = input.OpenId,
                OutTradeNo     = input.OutTradeNo ?? weChatPayHelper.GenerateOutTradeNo(),
                SpbillCreateIp = input.SpbillCreateIp,
                TimeExpire     = input.TimeExpire,
                TimeStart      = input.TimeStart,
                TotalFee       = ((int)(input.TotalFee * 100)).ToString(),
                NonceStr       = weChatPayHelper.GetNoncestr(),
                NotifyUrl      = config.PayNotifyUrl
            };
            var dictionary = weChatPayHelper.GetDictionaryByType(model);

            model.Sign = weChatPayHelper.CreateMd5Sign(dictionary, config.TenPayKey); //生成Sign

            var result = weChatPayHelper.PostXML <UnifiedorderResult>(url, model);

            if (result.IsSuccess())
            {
                var data = new
                {
                    appId     = result.AppId,
                    nonceStr  = result.NonceStr,
                    package   = "prepay_id=" + result.PrepayId,
                    signType  = "MD5",
                    timeStamp = weChatPayHelper.GetTimestamp()
                };
                return(new MiniProgramPayOutput
                {
                    AppId = data.appId,
                    Package = data.package,
                    NonceStr = data.nonceStr,
                    PaySign =
                        weChatPayHelper.CreateMd5Sign(weChatPayHelper.GetDictionaryByType(data), config.TenPayKey),
                    SignType = data.signType,
                    TimeStamp = data.timeStamp
                });
            }

            WeChatPayHelper.LoggerAction("Error", "支付错误:" + result.GetFriendlyMessage());
            throw new WeChatPayException("支付错误,请联系客服或重新支付!");
        }
예제 #5
0
        /**
         * 生成直接支付url,支付url有效期为2小时,模式二
         * @param productId 商品ID
         * @return 模式二URL
         */
        public UnifiedorderResponse GetPayUrl(UnifiedorderRequest orderRequest, SceneryDomain sceneryDomain)
        {
            WeChatQRCodeDomain qrCode = new WeChatQRCodeDomain();

            qrCode.BatchNumber = orderRequest.out_trade_no;
            qrCode.SceneryName = sceneryDomain.SceneryName;
            qrCode.Creater     = orderRequest.attach;
            qrCode.Updater     = orderRequest.attach;
            qrCode.Phone       = orderRequest.Phone;

            UnifiedorderResponse response = new UnifiedorderResponse();
            string out_trade_no           = GenerateSerialIdService.Get(FixedPrefix.WeChat, CustomPrefix.A, sceneryDomain.SceneryTCId.ToString()).SerialId;

            orderRequest.out_trade_no = out_trade_no;
            WxPayData data = new WxPayData();

            data.SetValue("body", orderRequest.body);                                             //商品描述
            data.SetValue("out_trade_no", out_trade_no);                                          //随机字符串
            data.SetValue("total_fee", Convert.ToInt32(orderRequest.total_fee));                  //总金额
            //10分钟 时间间隔
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));                 //交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间
            data.SetValue("trade_type", "NATIVE");                                                //交易类型
            data.SetValue("product_id", orderRequest.productId);                                  //商品ID
            data.SetValue("attach", orderRequest.attach);                                         //机器号


            string url = "";

            try
            {
                qrCode.Out_trade_no = orderRequest.out_trade_no;
                qrCode.RequestJson  = data.ToXml();
                WxPayData result = WxPayApi.UnifiedOrder(data, sceneryDomain.WeChat);//调用统一下单接口
                if (result.GetValue("return_code").ToString() == "SUCCESS")
                {
                    url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
                    LogHelper.WeChatLog(string.Format("请求成功,二维码地址:{0}", url));
                }
                else
                {
                    qrCode.Remark = result.GetValue("return_msg").ToString();
                    LogHelper.WeChatLog(string.Format("二维码地址请求失败:{0}", result.GetValue("return_msg")));
                }

                response.Out_trade_no = out_trade_no;
                response.QRCode       = url;

                qrCode.AppId  = sceneryDomain.WeChat.APPID;
                qrCode.QrCode = url;
            }
            catch (Exception ex)
            {
                qrCode.Remark = ex.Message;
                LogHelper.WeChatLog(string.Format("获取微信URL:请求失败,保存信息:{0}", ex.Message));
            }
            finally
            {
                try
                {
                    new WeChatQRCodeDao().Add(qrCode);
                }
                catch (Exception ex)
                {
                    LogHelper.WeChatLog(string.Format("获取微信URL:新增操作日志失败:{0}", ex.Message));
                }
            }
            return(response);
        }