示例#1
0
        /// <summary>
        /// 统一下单
        /// </summary>
        /// <param name="parameter">参数</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">传入的参数是null</exception>
        /// <exception cref="WeChatPayException">调用微信接口失败时返回的错误信息</exception>
        public async Task <UnifiedOrderResponse> UnifiedOrderAsync(UnifiedOrderRequest parameter)
        {
            parameter.AppId = _appId;
            parameter.MchId = _mchId;
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }
            if (parameter.TradeType == WeChatConstant.JsPay && string.IsNullOrEmpty(parameter.OpenId))
            {
                throw new WeChatPayException("支付方式JsPay OpenId 必须传入");
            }
            if (parameter.TradeType == WeChatConstant.NativePay && string.IsNullOrEmpty(parameter.ProductId))
            {
                throw new WeChatPayException("支付方式NativePay ProductId 必须传入");
            }
            parameter.Sign = WeChatSignHelper.CreateMd5Sign(parameter, _secretKey);
            string url    = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            string body   = XmlSerializeHelper.ObjectToXmlString(parameter);
            string result = await _client.ExecutePostRequest(url, new Dictionary <string, string>(),
                                                             body, "xml/text");

            var response = XmlSerializeHelper.StringToObject <UnifiedOrderResponse>(result);

            Check(response);
            return(response);
        }
示例#2
0
        /// <summary>
        ///  统一下单
        /// </summary>
        /// <param name="inputObj">提交给统一下单API的参数</param>
        /// <param name="timeOut">超时时间</param>
        /// <returns>成功时返回,其他抛异常</returns>
        public static WxApiResponse UnifiedOrder(UnifiedOrderRequest orderRequest, int timeOut = 6)
        {
            string            url      = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            WechatPaymentData inputObj = new WechatPaymentData();

            inputObj.SetValue("appid", orderRequest.AppId);                       //公众账号ID
            inputObj.SetValue("mch_id", orderRequest.Mch_Id);                     //商户号
            inputObj.SetValue("nonce_str", GenerateNonceStr());                   //随机字符串
            inputObj.SetValue("body", orderRequest.Body);                         //商品描述
            inputObj.SetValue("attach", orderRequest.Attach);                     //附加数据
            inputObj.SetValue("out_trade_no", orderRequest.Out_Trade_No);         //商城订单号
            inputObj.SetValue("total_fee", orderRequest.Total_Fee);               //总金额
            inputObj.SetValue("time_start", orderRequest.Time_Start);             //交易起始时间
            inputObj.SetValue("time_expire", orderRequest.Time_Expire);           //交易结束时间
            inputObj.SetValue("trade_type", orderRequest.Trade_Type.ToString());  //交易类型
            inputObj.SetValue("spbill_create_ip", orderRequest.Spbill_Create_Ip); //终端ip


            if (!orderRequest.Product_Id.IsNullOrEmpty())
            {
                inputObj.SetValue("product_id", orderRequest.Product_Id);//商品ID
            }
            if (orderRequest.Trade_Type == TradeType.JSAPI)
            {
                inputObj.SetValue("openid", orderRequest.OpenId);
            }
            else if (orderRequest.Trade_Type == TradeType.MWEB)
            {
                inputObj.SetValue("scene_info", orderRequest.Scene_Info);
            }


            if (!orderRequest.IsUseCredit)
            {
                inputObj.SetValue("limit_pay", "no_credit");
            }

            //签名
            inputObj.SetValue("sign", inputObj.MakeSign(orderRequest.Key));
            string xml = inputObj.ToXml();

            var start = DateTime.Now;

            string response = HttpTool.HttpRequest(url, xml, HttpRequestMethod.POST, HttpRequestDataFormat.Json, timeOut: timeOut);

            var end      = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            WechatPaymentData result = new WechatPaymentData();

            result.FromXml(response);


            return(new WxApiResponse(result));
        }
示例#3
0
        public void Validate_Request对象的外部属性为空_抛出异常()
        {
            //arrange
            UnifiedOrderRequest request = new UnifiedOrderRequest();

            //act
            TestDelegate testDelegate = () => request.Validate();

            //assert
            Assert.Throws <RequestParameterIsRequireException>(testDelegate);
        }
        public void Validate_Request对象的外部属性为空_抛出异常()
        {
            //arrange
            UnifiedOrderRequest request = new UnifiedOrderRequest();

            //act
            TestDelegate testDelegate = () => request.Validate();

            //assert
            Assert.Throws<RequestParameterIsRequireException>(testDelegate);
        }
示例#5
0
 /// <summary>
 /// 小程序支付统一下单
 /// </summary>
 public ApiResult <UnifiedOrderResponse> UnifiedOrder(UnifiedOrderRequest request)
 {
     if (request == null)
     {
         return(new ApiResult <UnifiedOrderResponse>()
         {
             message = "require parameters"
         });
     }
     else if (string.IsNullOrEmpty(request.body))
     {
         return(new ApiResult <UnifiedOrderResponse>()
         {
             message = "missing body"
         });
     }
     else if (string.IsNullOrEmpty(request.out_trade_no))
     {
         return(new ApiResult <UnifiedOrderResponse>()
         {
             message = "missing out_trade_no"
         });
     }
     else if (request.total_fee <= 0)
     {
         return(new ApiResult <UnifiedOrderResponse>()
         {
             message = "missing total_fee"
         });
     }
     else if (string.IsNullOrEmpty(request.spbill_create_ip))
     {
         return(new ApiResult <UnifiedOrderResponse>()
         {
             message = "missing spbill_create_ip"
         });
     }
     else if (string.IsNullOrEmpty(request.notify_url))
     {
         return(new ApiResult <UnifiedOrderResponse>()
         {
             message = "missing notify_url"
         });
     }
     else if (string.IsNullOrEmpty(request.openid) && request.trade_type == "JSAPI")
     {
         return(new ApiResult <UnifiedOrderResponse>()
         {
             message = "missing openid"
         });
     }
     return(GetResponseFromAsyncTask(UnifiedOrderAsync(request)));
 }
示例#6
0
        /// <summary>
        /// 创建支付信息(安卓 IOS)
        /// </summary>
        /// <param name="request">request</param>
        /// <param name="config">配置</param>
        /// <returns>结果</returns>
        public static UnifiedOrderResult CreateDirectPayByUser(UnifiedOrderRequest request, Config config)
        {
            // 统一下单
            var requestStr         = TenpayUtil.GetUnifiedOrderXml(request, config);
            var response           = HttpHelp.PostXmlToUrl(Config.UnifiedPayUrl, requestStr);
            var unifiedOrderResult = TenpayUtil.ConvertToUnifiedOrderResult(response);
            // 调起支付
            var parameters = TenpayUtil.GetPaySign(unifiedOrderResult, config);
            var result     = TenpayUtil.CreatePayParameters(parameters, unifiedOrderResult);

            return(result);
        }
示例#7
0
        /// <summary>
        /// 小程序支付统一下单
        /// </summary>
        /// <param name="trade_no"></param>
        /// <param name="total_fee"></param>
        /// <param name="body"></param>
        /// <param name="spbill_create_ip"></param>
        /// <param name="notify_url"></param>
        /// <param name="trade_type"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public ApiResult <UnifiedOrderResponse> UnifiedOrder(String trade_no, Int32 total_fee, String body, String spbill_create_ip, String notify_url, String trade_type, String openid)
        {
            var request = new UnifiedOrderRequest();

            request.out_trade_no     = trade_no;
            request.body             = body;
            request.total_fee        = total_fee;
            request.spbill_create_ip = spbill_create_ip;
            request.notify_url       = notify_url;
            request.trade_type       = trade_type;
            request.openid           = openid;
            return(UnifiedOrder(request));
        }
示例#8
0
        /// <summary>
        /// 商户系统先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易会话标识后再在APP里面调起支付。
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <UnifiedOrderResponse> UnifiedOrder(UnifiedOrderRequest request)
        {
            using (var http = new HttpClient())
            {
                var responseMessage = await http.PostAsync("https://api.mch.weixin.qq.com/pay/unifiedorder",
                                                           new XmlContent <UnifiedOrderRequest>(request));

                var responseXmlString = await responseMessage.Content.ReadAsStringAsync();

                var response = ToResponse <UnifiedOrderResponse>(responseXmlString);

                return(response);
            }
        }
        /// <summary>
        /// 应用需要先调用本接口生成支付订单号,并将应答的pay_info透传给聚鑫SDK,拉起客户端(包括微信公众号/微信小程序/客户端App)支付。
        /// </summary>
        /// <param name="req"><see cref="UnifiedOrderRequest"/></param>
        /// <returns><see cref="UnifiedOrderResponse"/></returns>
        public async Task <UnifiedOrderResponse> UnifiedOrder(UnifiedOrderRequest req)
        {
            JsonResponseModel <UnifiedOrderResponse> rsp = null;

            try
            {
                var strResp = await this.InternalRequest(req, "UnifiedOrder");

                rsp = JsonConvert.DeserializeObject <JsonResponseModel <UnifiedOrderResponse> >(strResp);
            }
            catch (JsonSerializationException e)
            {
                throw new TencentCloudSDKException(e.Message);
            }
            return(rsp.Response);
        }
        public void Validate_UnifiedOrderRequest在TradeType为NATIVE和ProductId为空的情况_抛出异常()
        {
            //arrange
            UnifiedOrderRequest request = new UnifiedOrderRequest();
            request.Desc = "Temp";
            request.TradeNum = "Temp";
            request.TotalFee = 100;
            request.SpbillCreateIp = "Temp";
            request.TradeType = "NATIVE";
  
            //act
            TestDelegate testDelegate = () => request.Validate();

            //assert
            Assert.Throws<RequestParameterIsRequireException>(testDelegate);
        }
示例#11
0
        public async Task UnifiedOrderNative()
        {
            string nonce     = Caster.WeChat.Common.Helper.GetNonceStr(32);
            string orderCode = Caster.WeChat.Common.Helper.GetTimestamp().ToString();
            var    parameter = new UnifiedOrderRequest(nonce, "测试", orderCode, 100, "123.185.181.156",
                                                       "http://www.eyu360.com/WeChatPay/NormalPayCallback", "NATIVE")
            {
                ProductId = "0213"
            };
            var result = await _web.PayService.UnifiedOrderAsync(parameter);

            Assert.True(
                result.ReturnCode == WeChatConstant.PaySuccess && result.ResultCode == WeChatConstant.PaySuccess,
                "result.ReturnCode ==WeChatConstant.PaySuccess && result.ResultCode ==WeChatConstant.PaySuccess");
            _output.WriteLine(result.CodeUrl);
        }
示例#12
0
        public CreateOrderResult CreateOrderAsync(CreateOrderParameter createOrderParameter)
        {
            string str;

            if (!this.ValidateParameter <CreateOrderParameter>(createOrderParameter, out str))
            {
                CreateOrderResult result1 = new CreateOrderResult();
                result1.ErrorMessage = str;
                return(result1);
            }
            UnifiedOrderRequest request = new UnifiedOrderRequest
            {
                AppId         = this.m_AppId,
                MerchantId    = createOrderParameter.MerchantId,
                DeviceInfo    = _DeviceInfo,
                NonceString   = WeChatSignHelper.CreateRandomString(),
                Body          = createOrderParameter.Body,
                Detail        = createOrderParameter.Detail,
                Attach        = createOrderParameter.Attach,
                OutTradeNo    = createOrderParameter.OutTradeNo,
                FeeType       = _OrderFeeType,
                TotalFee      = (int)(createOrderParameter.TotalFee * 100.0),
                SpbllCreateIP = createOrderParameter.IP,
                TimeStart     = DateTime.Now.ToString("yyyyMMddHHmmss"),
                TimeExpire    = DateTime.Now.AddHours((double)_OrderExpireHour).ToString("yyyyMMddHHmmss"),
                NotifyUrl     = createOrderParameter.NotifyUrl,
                TradeType     = createOrderParameter.TradeType,
                ProductId     = createOrderParameter.ProductId,
                OpenId        = createOrderParameter.OpenId
            };
            UnifiedOrderResponse response = this.InvokeApiAsync <UnifiedOrderRequest, UnifiedOrderResponse>(_UnifiedorderUrl, request);

            if (!response.IsSuccess)
            {
                CreateOrderResult result3 = new CreateOrderResult();
                result3.ErrorCode    = response.ErrCode;
                result3.ErrorMessage = response.ReturnMsg;
                return(result3);
            }
            CreateOrderResult result2 = new CreateOrderResult();

            result2.IsSuccess = true;
            result2.CodeUrl   = response.CodeUrl;
            result2.PrepayId  = response.PrepayId;
            return(result2);
        }
示例#13
0
        public void Validate_UnifiedOrderRequest在TradeType为NATIVE和ProductId为空的情况_抛出异常()
        {
            //arrange
            UnifiedOrderRequest request = new UnifiedOrderRequest();

            request.Desc           = "Temp";
            request.TradeNum       = "Temp";
            request.TotalFee       = 100;
            request.SpbillCreateIp = "Temp";
            request.TradeType      = "NATIVE";

            //act
            TestDelegate testDelegate = () => request.Validate();

            //assert
            Assert.Throws <RequestParameterIsRequireException>(testDelegate);
        }
示例#14
0
        public void Validate_填满UnifiedOrderRequest对象的必备参数_不发生异常()
        {
            //arrange
            UnifiedOrderRequest request = new UnifiedOrderRequest();

            request.Desc           = "Temp";
            request.TradeNum       = "Temp";
            request.TotalFee       = 100;
            request.SpbillCreateIp = "Temp";
            request.TradeType      = "Temp";
            request.NotifyUrl      = "www.baidu.com";
            request.NonceStr       = "123456789";

            //act
            request.Validate();

            //assert
        }
        public void Validate_填满UnifiedOrderRequest对象的必备参数_不发生异常()
        {
            //arrange
            UnifiedOrderRequest request = new UnifiedOrderRequest();
            request.Desc = "Temp";
            request.TradeNum = "Temp";
            request.TotalFee = 100;
            request.SpbillCreateIp = "Temp";
            request.TradeType = "Temp";
            request.NotifyUrl = "www.baidu.com";
            request.NonceStr = "123456789";

            //act  
            request.Validate();

            //assert    
            
        }
示例#16
0
        /// <summary>
        /// 微信统一下单接口xml参数整理
        /// </summary>
        /// <param name="request">微信支付参数实例</param>
        /// <param name="config">config</param>
        /// <returns>xml</returns>
        public static string GetUnifiedOrderXml(UnifiedOrderRequest request, Config config)
        {
            SortedDictionary <string, string> sParams = new SortedDictionary <string, string>
            {
                { "appid", config.GetAppId() },
                { "mch_id", config.GetPid() },
                { "nonce_str", Config.GetNoncestr() },
                { "body", request.Body },
                { "out_trade_no", request.OutTradeNo },
                { "total_fee", request.TotalFee.ToString() },
                { "spbill_create_ip", request.SpbillCreateIp },
                { "notify_url", request.NotifyUrl },
                { "trade_type", "APP" }
            };

            if (!string.IsNullOrEmpty(request.Detail))
            {
                sParams.Add("detail", request.Detail);
            }
            var sign = Signature.Getsign(sParams, config.GetKey());

            sParams.Add("sign", sign);

            //拼接成XML请求数据
            StringBuilder sbPay = new StringBuilder();

            foreach (KeyValuePair <string, string> k in sParams)
            {
                if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                {
                    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                }
                else
                {
                    sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                }
            }
            var return_string = $"<xml>{sbPay}</xml>";

            return(return_string);
        }
        public void GetParameterDict_UnifiedOrderRequest输入正常的外部属性_结果匹配()
        {
            //arrange
            UnifiedOrderRequest request = new UnifiedOrderRequest();
            request.Desc = "Desc";
            request.TradeNum = "TradeNum";
            request.TotalFee = 100;
            request.SpbillCreateIp = "SpbillCreateIp";
            request.TradeType = "TradeType";

            //act
            Dictionary<string, string> target = request.GetParameterDict();

            //assert
            Assert.IsTrue(target.Count == 5);
            Assert.IsTrue(target["body"] == "Desc");
            Assert.IsTrue(target["out_trade_no"] == "TradeNum");
            Assert.IsTrue(target["total_fee"] == "100");
            Assert.IsTrue(target["spbill_create_ip"] == "SpbillCreateIp");
            Assert.IsTrue(target["trade_type"] == "TradeType");
        } 
示例#18
0
        public async Task <UnifiedOrderPayParamsResponse> Unifiedorder(string openId, decimal amount, string notifyPath, string productId, string body, string attach)
        {
            var unifiedOrderReq = new UnifiedOrderRequest(
                _weixinSetting.AppID,
                _weixinSetting.MchId,
                _weixinSetting.PartnerKey,
                body,
                amount,
                "192.168.99.1",
                notifyPath,
                openId);

            unifiedOrderReq.attach     = attach;
            unifiedOrderReq.detail     = body;
            unifiedOrderReq.product_id = productId;
            unifiedOrderReq.sign       = Utility.MakeSign(unifiedOrderReq, _weixinSetting.PartnerKey);

            var unifiedOrderResp = await _clientService.ExecuteAsync(unifiedOrderReq, RequestStringDataTypes.Xml);

            var payParams = new UnifiedOrderPayParamsResponse();

            payParams.returnCode = unifiedOrderResp.return_code;
            payParams.returnMsg  = unifiedOrderResp.return_msg;

            if (unifiedOrderResp.return_code == "SUCCESS")
            {
                payParams.appId     = _weixinSetting.AppID;
                payParams.nonceStr  = Utility.GenerateNonceStr();
                payParams.package   = string.Format("prepay_id={0}", unifiedOrderResp.prepay_id);
                payParams.timeStamp = Utility.GenerateTimeStamp();
                payParams.signType  = "MD5";

                payParams.OpenId     = openId;
                payParams.OutTradeNo = unifiedOrderReq.out_trade_no;
                payParams.paySign    = Utility.MakeSign(payParams, _weixinSetting.PartnerKey);
            }

            return(payParams);
        }
示例#19
0
        public void GetParameterDict_UnifiedOrderRequest输入正常的外部属性_结果匹配()
        {
            //arrange
            UnifiedOrderRequest request = new UnifiedOrderRequest();

            request.Desc           = "Desc";
            request.TradeNum       = "TradeNum";
            request.TotalFee       = 100;
            request.SpbillCreateIp = "SpbillCreateIp";
            request.TradeType      = "TradeType";

            //act
            Dictionary <string, string> target = request.GetParameterDict();

            //assert
            Assert.IsTrue(target.Count == 5);
            Assert.IsTrue(target["body"] == "Desc");
            Assert.IsTrue(target["out_trade_no"] == "TradeNum");
            Assert.IsTrue(target["total_fee"] == "100");
            Assert.IsTrue(target["spbill_create_ip"] == "SpbillCreateIp");
            Assert.IsTrue(target["trade_type"] == "TradeType");
        }
示例#20
0
        //支付接口
        async Task <UnifiedOrderResponse> IWechatPay.Pay(UnifiedOrderRequest unifiedOrder)
        {
            //生成请求字段集合原料
            var properties = this.GenerateCommonRequestEntity();

            properties.Add("notify_url", this._settings.PaymentNotifyURI);

            //填充请求字段集合
            this.FillRequestEntity(ref properties, unifiedOrder, this._payRequireProperties);

            //获取响应
            UnifiedOrderResponse response = await this.CallAsync <UnifiedOrderResponse>(
                Constant.UnifiedOrder, properties);

            //检验响应体合法性
            if (this.CheckResponseLegal(response))
            {
                return(response);
            }
            else
            {
                return(null);
            }
        }
示例#21
0
        /// <summary>
        /// 支付
        /// </summary>
        /// <param name="id"></param>
        /// <param name="openId"></param>
        /// <param name="mark"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult CheckOut(string code, string orderNo)
        {
            string openid = "";

            if (new AppSetting().IsDebug != null &&
                new AppSetting().IsDebug.ToLower() == "true")
            {
                openid = "123";
            }
            else
            {
                if (Request.Cookies[SystemConfig.WXOpenIDCookieKey] != null)
                {
                    openid = Request.Cookies[SystemConfig.WXOpenIDCookieKey].Value;
                }

                if (string.IsNullOrWhiteSpace(openid) && code == null)
                {
                    Response.Redirect(CommonHelper.GetRedirect("WxClass%2fClassList"));
                }
                try
                {
                    if (string.IsNullOrWhiteSpace(openid))
                    {
                        openid = GetOpenId(code).openid;


                        // 合法用户,允许访问
                        Response.Cookies[SystemConfig.WXOpenIDCookieKey].Value   = openid;
                        Response.Cookies[SystemConfig.WXOpenIDCookieKey].Path    = "/";
                        Response.Cookies[SystemConfig.WXOpenIDCookieKey].Expires = DateTime.Now.AddDays(1);
                    }
                }
                catch (Exception ex)
                {
                }
            }

            try
            {
                AppSetting  setting = new AppSetting();
                WxPayClient client  = new WxPayClient();

                OrderBC bc = new OrderBC();

                var order = bc.GetOrderByOrderNo(orderNo);

                string outTradeNumber = string.Format("{0}{1}", orderNo.ToString(), DateTime.Now.ToString("fff"));



                UnifiedOrderRequest req = new UnifiedOrderRequest();
                req.Body   = "万韬财税课程购买";        //商品描述-----------------------
                req.Attach = openid.ToString(); //附加信息,会原样返回,充值人员微信Openid

                req.GoodTag    = "Pay";
                req.TradeType  = "JSAPI";
                req.OpenId     = openid;
                req.OutTradeNo = outTradeNumber;   //---商户订单号----------------
                req.TotalFee   = 1;                //测试总金额
                //req.TotalFee = Convert.ToInt32(order.PayPrice * 100);//总金额
                req.NotifyUrl = setting.NotifyUrl; //异步通知地址-------------------------
                var resp = client.UnifiedOrder(req);

                WxPayData jsApiParam = new WxPayData();
                jsApiParam.SetValue("appId", resp.AppId);
                jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
                jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
                jsApiParam.SetValue("package", "prepay_id=" + resp.PrepayId);
                jsApiParam.SetValue("signType", "MD5");
                jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

                bc.UpdatePayInfo(outTradeNumber, jsApiParam.ToJson(), orderNo);

                //--给Viewbag赋值,供前台页面jsapi调用
                ViewBag.AppId     = (string)jsApiParam.GetValue("appId");
                ViewBag.Package   = (string)jsApiParam.GetValue("package");
                ViewBag.NonceStr  = (string)jsApiParam.GetValue("nonceStr");
                ViewBag.Paysign   = (string)jsApiParam.GetValue("paySign");
                ViewBag.TimeStamp = (string)jsApiParam.GetValue("timeStamp");
                ViewBag.OpenId    = openid;
                ViewBag.OrderNo   = orderNo;


                ViewBag.OpenId  = openid;
                ViewBag.OrderNo = orderNo;
            }
            catch (Exception ex)
            {
            }
            return(View());
        }
示例#22
0
 /// <summary>
 /// 小程序支付统一下单 的异步形式。
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public Task <ApiResult <UnifiedOrderResponse> > UnifiedOrderAsync(UnifiedOrderRequest request)
 {
     request.body = request.body.Replace("&", "");
     return(CallAsync <UnifiedOrderRequest, UnifiedOrderResponse>("unifiedorder", request, System.Net.Http.HttpMethod.Get));
 }