CreateMd5Sign() public method

创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名
public CreateMd5Sign ( string key, string value ) : string
key string 参数名
value string 参数值
return string
示例#1
0
        /// <summary>
        /// 获取微信支付必要的参数
        /// </summary>
        /// <param name="prepayId">微信预支付订单号</param>
        /// <param name="timeStamp">时间戳</param>
        /// <param name="nonceStr">随机数</param>
        /// <returns></returns>
        public TenPayV3_JsApi TenPayV3Info(string prepayId, string timeStamp = null, string nonceStr = null)
        {
            string paySign = "";

            nonceStr  = string.IsNullOrEmpty(nonceStr) ? TenPayUtil.GetNoncestr() : nonceStr;
            timeStamp = string.IsNullOrEmpty(timeStamp) ? TenPayUtil.GetTimestamp() : timeStamp;

            //设置支付参数
            RequestHandler paySignReqHandler = new RequestHandler(null);

            paySignReqHandler.SetParameter("appId", AppId);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySign = paySignReqHandler.CreateMd5Sign("key", Key);
            TenPayV3_JsApi tenPayV3JsApi = new TenPayV3_JsApi()
            {
                AppId     = AppId,
                NonceStr  = nonceStr,
                TimeStamp = timeStamp,
                Package   = string.Format("prepay_id={0}", prepayId),
                PaySign   = paySign
            };

            return(tenPayV3JsApi);
        }
示例#2
0
        /// <summary>
        /// 获取预支付订单
        /// </summary>
        /// <param name="orderId">订单号</param>
        /// <param name="body">支付主体内容</param>
        /// <param name="spbillCreateIp">IP</param>
        /// <param name="openId"></param>
        /// <param name="price"></param>
        /// <param name="parentId">返回的预支付订单【2小时有效】</param>
        /// <param name="nonceStr"></param>
        /// <returns></returns>
        public string GetCodeUrl(string orderId, string body, string spbillCreateIp, decimal price, out string parentId,
                                 string nonceStr = null)
        {
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);

            //初始化
            packageReqHandler.Init();

            nonceStr = string.IsNullOrEmpty(nonceStr) ? TenPayUtil.GetNoncestr() : nonceStr;

            //设置package订单参数
            packageReqHandler.SetParameter("appid", AppId);                           //公众账号ID
            packageReqHandler.SetParameter("mch_id", MchId);                          //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                    //随机字符串
            packageReqHandler.SetParameter("body", body);
            packageReqHandler.SetParameter("out_trade_no", orderId);                  //商家订单号
            packageReqHandler.SetParameter("total_fee", (price * 100).ToString("0")); //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", spbillCreateIp);       //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", TenPayV3Notify);             //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", "NATIVE");                   //交易类型
                                                                                      //packageReqHandler.SetParameter("openid", openId); //用户的openid
            string sign = packageReqHandler.CreateMd5Sign("key", Key);

            packageReqHandler.SetParameter("sign", sign); //签名

            string data = packageReqHandler.ParseXML();

            var result = TenPayV3.Unifiedorder(data);

            LogUtility.DebugLogger.Info(result);

            var res = XDocument.Parse(result);

            //LogUtility.Order.Error(string.Format("预支付订单返回XML :{0}", result));
            if (res.Element("xml") == null)
            {
                throw new Exception("统一订单接口出错");
            }
            var codeUrl = res.Element("xml").Element("code_url") == null
               ? null
               : res.Element("xml").Element("code_url").Value;

            parentId = res.Element("xml").Element("prepay_id") == null
              ? null
              : res.Element("xml").Element("prepay_id").Value;
            if (string.IsNullOrEmpty(codeUrl))
            {
                throw new Exception("统一订单接口出错,未获取到预支付订单号");
            }
            return(codeUrl);
        }
        /// <summary>
        /// 关闭订单接口
        /// </summary>
        /// <returns></returns>
        public ActionResult CloseOrder()
        {
            string nonceStr = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		  //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);		  //商户号
            packageReqHandler.SetParameter("out_trade_no", "");                 //填入商家订单号
            packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            packageReqHandler.SetParameter("sign", sign);	                    //签名

            string data = packageReqHandler.ParseXML();

            var result = TenPayV3.CloseOrder(data);
            var res = XDocument.Parse(result);
            string openid = res.Element("xml").Element("openid").Value;

            return Content(openid);
        }
        /// <summary>
        /// 刷卡支付
        /// </summary>
        /// <param name="authCode">扫码设备获取到的微信用户刷卡授权码</param>
        /// <returns></returns>
        public ActionResult MicroPay(string authCode)
        {
            RequestHandler payHandler = new RequestHandler(null);

            var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            var nonceStr = TenPayV3Util.GetNoncestr();

            payHandler.SetParameter("auth_code", authCode);//授权码
            payHandler.SetParameter("body", "test");//商品描述
            payHandler.SetParameter("total_fee", "1");//总金额
            payHandler.SetParameter("out_trade_no", sp_billno);//产生随机的商户订单号
            payHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);//终端ip
            payHandler.SetParameter("appid", TenPayV3Info.AppId);//公众账号ID
            payHandler.SetParameter("mch_id", TenPayV3Info.MchId);//商户号
            payHandler.SetParameter("nonce_str", nonceStr);//随机字符串

            string sign = payHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            payHandler.SetParameter("sign", sign);//签名

            var result = TenPayV3.MicroPay(payHandler.ParseXML());

            //此处只是完成最简单的支付功能,实际情况还需要考虑各种出错的情况,并处理错误,最后返回结果通知用户。

            return Content(result);
        }
示例#5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int orderId = MyCommFun.RequestInt("orderid");
            int wid     = MyCommFun.RequestInt("wid");

            getwid     = wid;
            getorderId = orderId;
            string code  = MyCommFun.RequestParam("code");
            string state = MyCommFun.RequestParam("state");

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);
            BLL.wx_userweixin      wx          = new BLL.wx_userweixin();
            Model.wx_userweixin    wxModel     = wx.GetModel(wid);
            BLL.orders             otBll       = new BLL.orders();

            Model.orders orderEntity = otBll.GetModel(orderId, wid);

            litout_trade_no = orderEntity.order_no;
            litMoney        = Decimal.ToInt32(orderEntity.order_amount);
            litDate         = orderEntity.add_time.ToString();



            if (string.IsNullOrEmpty(code))
            {
                Response.Write("您拒绝了授权!");
                return;
            }

            if (!state.Contains("|"))
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                Response.Write("验证失败!请从正规途径进入!1001");
                return;
            }

            ////获取产品信息
            //var stateData = state.Split('|');
            //int productId = 0;

            //if (int.TryParse(stateData[0], out productId))
            //{
            //    int hc = 0;
            //    if (int.TryParse(stateData[1], out hc))
            //    {
            //        var products = ProductModel.GetFakeProductList();
            //        product = products.FirstOrDefault(z => z.Id == productId);
            //        if (product == null || product.GetHashCode() != hc)
            //        {
            //            return Content("商品信息不存在,或非法进入!1002");
            //        }
            //        ViewData["product"] = product;
            //    }
            //}

            //通过,用code换取access_token
            var openIdResult = OAuthApi.GetAccessToken(PayV3Config.Mch_appId, PayV3Config.Mch_Secret, code);

            if (openIdResult.errcode != ReturnCode.请求成功)
            {
                Response.Write("错误:" + openIdResult.errmsg);
                return;
            }

            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";

            string sp_billno = Request["order_no"];
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            }
            else
            {
                sp_billno = Request["order_no"].ToString();
            }

            //创建支付应答对象
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //初始化
            packageReqHandler.Init();

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

            //设置package订单参数
            //  packageReqHandler.SetParameter("appid", paymentInfo.appId);		  //公众账号ID
            ///    packageReqHandler.SetParameter("mch_id", paymentInfo.partnerId);		  //商户号

            packageReqHandler.SetParameter("appid", PayV3Config.Mch_appId);               //公众账号ID
            packageReqHandler.SetParameter("mch_id", PayV3Config.Mch_mchid);              //商户号
            ////
            packageReqHandler.SetParameter("sub_appid", paymentInfo.appId);               //子商户公众账号ID
            packageReqHandler.SetParameter("sub_mch_id", paymentInfo.partnerId);          //子商户号mch_id
            ///


            packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                          //随机字符串
            packageReqHandler.SetParameter("body", orderId.ToString());                                                                     //商品信息
            packageReqHandler.SetParameter("out_trade_no", litout_trade_no);                                                                //商家订单号
            packageReqHandler.SetParameter("total_fee", (litMoney * 100).ToString());                                                       //product == null ? "100" : (product.Price * 100).ToString()商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                                                    //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", MyCommFun.getWebSite() + "/api/wxpay/notify_url.aspx?wid=" + wid + "|" + orderId); //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                    //交易类型
            packageReqHandler.SetParameter("openid", openIdResult.openid);                                                                  //用户的openId

            //   string sign = packageReqHandler.CreateMd5Sign("key", paymentInfo.paySignKey);
            string sign = packageReqHandler.CreateMd5Sign("key", PayV3Config.Mch_Key);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var result = TenPayV3.Unifiedorder(data);

            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", PayV3Config.Mch_appId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", PayV3Config.Mch_Key);



            payaddid        = PayV3Config.Mch_appId;
            paytimeStamp    = timeStamp;
            paynonceStr     = nonceStr;
            paypackageValue = string.Format("prepay_id={0}", prepayId);
            paypaySign      = paySign;
        }
        public ActionResult NativeNotifyUrl()
        {
            ResponseHandler resHandler = new ResponseHandler(null);

            //返回给微信的请求
            RequestHandler res = new RequestHandler(null);

            string openId = resHandler.GetParameter("openid");
            string productId = resHandler.GetParameter("product_id");

            if (openId == null || productId == null)
            {
                res.SetParameter("return_code", "FAIL");
                res.SetParameter("return_msg", "回调数据异常");
            }

            //创建支付应答对象
            //RequestHandler packageReqHandler = new RequestHandler(null);

            var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            var nonceStr = TenPayV3Util.GetNoncestr();

            //创建请求统一订单接口参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);
            //packageReqHandler.SetParameter("nonce_str", nonceStr);
            //packageReqHandler.SetParameter("body", "test");
            //packageReqHandler.SetParameter("out_trade_no", sp_billno);
            //packageReqHandler.SetParameter("total_fee", "1");
            //packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);
            //packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);
            //packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString());
            //packageReqHandler.SetParameter("openid", openId);
            //packageReqHandler.SetParameter("product_id", productId);

            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);

            //string data = packageReqHandler.ParseXML();

            var xmlDataInfo = new TenPayV3RequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "test", sp_billno, 1, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, productId, TenPayV3Info.Key, nonceStr);


            try
            {
                //调用统一订单接口
                var result = TenPayV3.Unifiedorder(xmlDataInfo);
                //var unifiedorderRes = XDocument.Parse(result);
                //string prepayId = unifiedorderRes.Element("xml").Element("prepay_id").Value;

                //创建应答信息返回给微信
                res.SetParameter("return_code", result.return_code);
                res.SetParameter("return_msg", result.return_msg ?? "OK");
                res.SetParameter("appid", result.appid);
                res.SetParameter("mch_id", result.mch_id);
                res.SetParameter("nonce_str", result.nonce_str);
                res.SetParameter("prepay_id", result.prepay_id);
                res.SetParameter("result_code", result.result_code);
                res.SetParameter("err_code_des", "OK");

                string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key);
                res.SetParameter("sign", result.sign);
            }
            catch (Exception)
            {
                res.SetParameter("return_code", "FAIL");
                res.SetParameter("return_msg", "统一下单失败");
            }

            return Content(res.ParseXML());
        }
        /// <summary>
        /// 目前支持向指定微信用户的openid发放指定金额红包
        /// 注意total_amount、min_value、max_value值相同
        /// total_num=1固定
        /// 单个红包金额介于[1.00元,200.00元]之间
        /// </summary>
        /// <returns></returns>
        public ActionResult SendRedPack()
        {
            string mchbillno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);

            string nonceStr = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            packageReqHandler.SetParameter("wxappid", TenPayV3Info.AppId);		  //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);		  //商户号
            packageReqHandler.SetParameter("mch_billno", mchbillno);                 //填入商家订单号
            packageReqHandler.SetParameter("nick_name", "提供方名称");                 //提供方名称
            packageReqHandler.SetParameter("send_name", "红包发送者名称");                 //红包发送者名称
            packageReqHandler.SetParameter("re_openid", "接受收红包的用户的openId");                 //接受收红包的用户的openId
            packageReqHandler.SetParameter("total_amount", "100");                //付款金额,单位分
            packageReqHandler.SetParameter("min_value", "100");                //最小红包金额,单位分
            packageReqHandler.SetParameter("max_value", "100");                //最大红包金额,单位分
            packageReqHandler.SetParameter("total_num", "1");               //红包发放总人数
            packageReqHandler.SetParameter("wishing", "红包祝福语");               //红包祝福语
            packageReqHandler.SetParameter("client_ip", Request.UserHostAddress);               //调用接口的机器Ip地址
            packageReqHandler.SetParameter("act_name", "活动名称");   //活动名称
            packageReqHandler.SetParameter("remark", "备注信息");   //备注信息
            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            packageReqHandler.SetParameter("sign", sign);	                    //签名
            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = @"F:\apiclient_cert.p12";
            //私钥(在安装证书时设置)
            string password = "";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();
            #endregion

            return Content(responseContent);
        }
        /// <summary>
        /// 企业支付TEST
        /// </summary>
        /// <param name="openId">openId</param>
        /// <param name="orderId">订单号</param>
        /// <param name="amount">金额</param>
        /// <param name="desc">付款描述信息</param>
        /// <returns></returns>
        public ContentResult QyPayTest(string openId,string orderId,decimal amount,string desc)
        {
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);

            var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            var nonceStr = TenPayV3Util.GetNoncestr();

            //创建请求统一订单接口参数
            packageReqHandler.SetParameter("mch_appid", AppId);
            packageReqHandler.SetParameter("mchid", Mchid);
            packageReqHandler.SetParameter("nonce_str", nonceStr);
            packageReqHandler.SetParameter("partner_trade_no", orderId);
            packageReqHandler.SetParameter("openid", openId);
            packageReqHandler.SetParameter("check_name", "NO_CHECK");//不校验用户姓名
            packageReqHandler.SetParameter("desc", desc);
            packageReqHandler.SetParameter("amount", (amount * 100).ToString());
            packageReqHandler.SetParameter("spbill_create_ip", "101.200.233.5");//TODO:替换成可配置文件
            string sign = packageReqHandler.CreateMd5Sign("key", PayKey);
            packageReqHandler.SetParameter("sign", sign);

            string data = packageReqHandler.ParseXML();

            //证书相关
            var cert = new X509Certificate2(SSLCERT_PATH, SSLCERT_PASSWORD);

            try
            {
                //调用统一订单接口
                var result = TenPayV3.QYPay(data, cert);
                logger.Info(result);
                var unifiedorderRes = XDocument.Parse(result);
                string return_code = unifiedorderRes.Element("xml").Element("return_code").Value;
                return Content(return_code);
            }
            catch (Exception e)
            {
                logger.Error(e);
                return Content("-1");
            }

        }
示例#9
0
        /*
错误码	描述	解决方案
NO_AUTH	发放失败,此请求可能存在风险,已被微信拦截	请提醒用户检查自身帐号是否异常。使用常用的活跃的微信号可避免这种情况。
SENDNUM_LIMIT	该用户今日领取红包个数超过限制	如有需要、请在微信支付商户平台【api安全】中重新配置 【每日同一用户领取本商户红包不允许超过的个数】。
CA_ERROR	请求未携带证书,或请求携带的证书出错	到商户平台下载证书,请求带上证书后重试。
ILLEGAL_APPID	错误传入了app的appid	接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的)。
SIGN_ERROR	商户签名错误	按文档要求重新生成签名后再重试。
FREQ_LIMIT	受频率限制	请对请求做频率控制
XML_ERROR	请求的xml格式错误,或者post的数据为空	检查请求串,确认无误后重试
PARAM_ERROR	参数错误	请查看err_code_des,修改设置错误的参数
OPENID_ERROR	Openid错误	根据用户在商家公众账号上的openid,获取用户在红包公众账号上的openid 错误。请核对商户自身公众号appid和用户在此公众号下的openid。
NOTENOUGH	余额不足	商户账号余额不足,请登录微信支付商户平台充值
FATAL_ERROR	重复请求时,参数与原单不一致	使用相同商户单号进行重复请求时,参数与第一次请求时不一致,请检查并修改参数后再重试。
SECOND_OVER_LIMITED	企业红包的按分钟发放受限	每分钟发送红包数量不得超过1800个;(可联系微信支付[email protected]调高额度)
DAY_ OVER_LIMITED	企业红包的按天日发放受限	单个商户日发送红包数量不大于10000个;(可联系微信支付[email protected]调高额度)
MONEY_LIMIT	红包金额发放限制	每个红包金额必须大于1元,小于1000元(可联系微信支付[email protected]调高额度至4999元)
SEND_FAILED	红包发放失败,请更换单号再重试	原商户单号已经失败,如果还要对同一个用户发放红包, 需要更换新的商户单号再试。
SYSTEMERROR	系统繁忙,请再试。	可用同一商户单号再次调用,只会发放一个红包
PROCESSING	请求已受理,请稍后使用原单号查询发放结果	二十分钟后查询,按照查询结果成功失败进行处理
             */

        #endregion

        /// <summary>
        /// 普通红包发送
        /// </summary>
        /// <param name="appId">公众账号AppID</param>
        /// <param name="mchId">商户MchID</param>
        /// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
        /// <param name="tenPayCertPath">证书地址(硬盘物理地址,形如E:\\cert\\apiclient_cert.p12)</param>
        /// <param name="openId">要发红包的用户的OpenID</param>
        /// <param name="senderName">红包发送者名称,会显示给接收红包的用户</param>
        /// <param name="iP">发送红包的服务器地址</param>
        /// <param name="redPackAmount">红包金额(单位分)</param>
        /// <param name="wishingWord">祝福语</param>
        /// <param name="actionName">活动名称</param>
        /// <param name="remark">活动描述,用于低版本微信显示</param>
        /// <param name="nonceStr">将nonceStr随机字符串返回,开发者可以存到数据库用于校验</param>
        /// <param name="paySign">将支付签名返回,开发者可以存到数据库用于校验</param>
        /// <param name="scene">场景id(非必填)</param>
        /// <param name="riskInfo">活动信息(非必填),String(128)posttime:用户操作的时间戳。
        /// <para>示例:posttime%3d123123412%26clientversion%3d234134%26mobile%3d122344545%26deviceid%3dIOS</para>
        /// <para>mobile:业务系统账号的手机号,国家代码-手机号。不需要+号</para>
        /// <para>deviceid :mac 地址或者设备唯一标识</para>
        /// <para>clientversion :用户操作的客户端版本</para>
        /// <para>把值为非空的信息用key = value进行拼接,再进行urlencode</para>
        /// <para>urlencode(posttime= xx & mobile = xx & deviceid = xx)</para>
        /// </param>
        /// <param name="consumeMchId">资金授权商户号,服务商替特约商户发放时使用(非必填),String(32)。示例:1222000096</param>
        /// <returns></returns>
        public static NormalRedPackResult SendNormalRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath,
            string openId, string senderName,
            string iP, int redPackAmount, string wishingWord, string actionName, string remark,
            out string nonceStr, out string paySign, RedPack_Scene? scene = null, string riskInfo = null, string consumeMchId = null)
        {
            string mchbillno = GetNewBillNo(mchId);

            nonceStr = TenPayV3Util.GetNoncestr();
            //RequestHandler packageReqHandler = new RequestHandler(null);

            //string accessToken = AccessTokenContainer.GetAccessToken(ConstantClass.AppID);
            //UserInfoJson userInforResult = UserApi.Info(accessToken, openID);

            RequestHandler packageReqHandler = new RequestHandler();
            //设置package订单参数
            packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            packageReqHandler.SetParameter("wxappid", appId);		  //公众账号ID
            packageReqHandler.SetParameter("mch_id", mchId);		  //商户号
            packageReqHandler.SetParameter("mch_billno", mchbillno);                 //填入商家订单号
            packageReqHandler.SetParameter("send_name", senderName);                //红包发送者名称
            packageReqHandler.SetParameter("re_openid", openId);                 //接受收红包的用户的openId
            packageReqHandler.SetParameter("total_amount", redPackAmount.ToString());                //付款金额,单位分
            packageReqHandler.SetParameter("total_num", "1");               //红包发放总人数
            packageReqHandler.SetParameter("wishing", wishingWord);               //红包祝福语
            packageReqHandler.SetParameter("client_ip", iP);               //调用接口的机器Ip地址
            packageReqHandler.SetParameter("act_name", actionName);   //活动名称
            packageReqHandler.SetParameter("remark", remark);   //备注信息
            paySign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
            packageReqHandler.SetParameter("sign", paySign);	                    //签名

            if (scene.HasValue)
            {
                packageReqHandler.SetParameter("scene_id", scene.Value.ToString());//场景id
            }
            if (riskInfo != null)
            {
                packageReqHandler.SetParameter("risk_info", riskInfo);//活动信息	
            }
            if (consumeMchId != null)
            {
                packageReqHandler.SetParameter("consume_mch_id", consumeMchId);//活动信息	
            }

            //最新的官方文档中将以下三个字段去除了
            //packageReqHandler.SetParameter("nick_name", "提供方名称");                 //提供方名称
            //packageReqHandler.SetParameter("max_value", "100");                //最大红包金额,单位分
            //packageReqHandler.SetParameter("min_value", "100");                //最小红包金额,单位分

            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = tenPayCertPath;
            //私钥(在安装证书时设置)
            string password = mchId;

            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //X509Certificate cer = new X509Certificate(cert, password);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";


            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();
            #endregion

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(responseContent);

            //XDocument xDoc = XDocument.Load(responseContent);

            NormalRedPackResult normalReturn = new NormalRedPackResult
            {
                err_code = "",
                err_code_des = ""
            };

            if (doc.SelectSingleNode("/xml/return_code") != null)
            {
                normalReturn.return_code = (doc.SelectSingleNode("/xml/return_code").InnerText.ToUpper() == "SUCCESS");
            }
            if (doc.SelectSingleNode("/xml/return_msg") != null)
            {
                normalReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
            }

            if (normalReturn.return_code == true)
            {
                //redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
                if (doc.SelectSingleNode("/xml/result_code") != null)
                {
                    normalReturn.result_code = (doc.SelectSingleNode("/xml/result_code").InnerText.ToUpper() == "SUCCESS");
                }

                if (normalReturn.result_code == true)
                {
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }

                    //裂变红包才有
                    if (doc.SelectSingleNode("/xml/send_time") != null)
                    {
                        normalReturn.send_time = doc.SelectSingleNode("/xml/send_time").InnerText;
                    }
                    //裂变红包才有
                    if (doc.SelectSingleNode("/xml/send_listid") != null)
                    {
                        normalReturn.send_listid = doc.SelectSingleNode("/xml/send_listid").InnerText;
                    }
                }
                else
                {
                    if (doc.SelectSingleNode("/xml/err_code") != null)
                    {
                        normalReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/err_code_des") != null)
                    {
                        normalReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }

                }
            }

            return normalReturn;
        }
        /// <summary>
        /// 关闭订单 请求参数
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="mchId"></param>
        /// <param name="outTradeNo"></param>
        /// <param name="key"></param>
        /// <param name="nonceStr"></param>
        /// <param name="signType"></param>
        public TenPayV3CloseOrderRequestData(string appId, string mchId, string outTradeNo, string key, string nonceStr,
            string signType = "MD5")
        {
            AppId = appId;
            MchId = mchId;
            NonceStr = nonceStr;
            OutTradeNo = outTradeNo;
            SignType = signType;
            Key = key;

            #region 设置RequestHandler

            //创建支付应答对象
            PackageRequestHandler = new RequestHandler(null);
            //初始化
            PackageRequestHandler.Init();

            //设置package订单参数
            PackageRequestHandler.SetParameter("appid", this.AppId); //公众账号ID
            PackageRequestHandler.SetParameter("mch_id", this.MchId); //商户号
            PackageRequestHandler.SetParameter("out_trade_no", this.OutTradeNo); //填入商家订单号
            PackageRequestHandler.SetParameter("nonce_str", this.NonceStr); //随机字符串
            Sign = PackageRequestHandler.CreateMd5Sign("key", this.Key);
            PackageRequestHandler.SetParameter("sign", Sign); //签名

            #endregion
        }
示例#11
0
        private bool PreparePaySign(TradeOrder order, out string appId, out string timeStamp,
            out string nonceStr, out string package, out string paySign, out string message)
        {
            bool isSuccessFul = false;

            appId = string.Empty;
            timeStamp = string.Empty;
            nonceStr = string.Empty;
            package = string.Empty;
            paySign = string.Empty;

            message = string.Empty;

            try
            {

                //创建支付应答对象
                RequestHandler packageReqHandler = new RequestHandler(null);
                //初始化
                packageReqHandler.Init();

                appId = TenPayV3Info.AppId;
                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr = TenPayV3Util.GetNoncestr();

                string body = "活动在线网-购买需求联系方式";

                //设置package订单参数
                packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		  //公众账号ID
                packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);		  //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                    //随机字符串
                packageReqHandler.SetParameter("body", body);    //商品信息
                packageReqHandler.SetParameter("out_trade_no", order.OrderId);		//商家订单号
                packageReqHandler.SetParameter("total_fee", (Convert.ToInt32(order.Amount * 100).ToString()));			        //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);   //用户的公网ip,不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);		    //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());	                    //交易类型
                packageReqHandler.SetParameter("openid", CurrentWeChatUser.OpenId);	                    //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
                packageReqHandler.SetParameter("sign", sign);	                    //签名

                string data = packageReqHandler.ParseXML();

                var result = TenPayV3.Unifiedorder(data);
                var res = XDocument.Parse(result);

                LogService.LogWexin("微信支付参数", res.ToString());
                string prepayId = res.Element("xml").Element("prepay_id").Value;

                //设置支付参数
                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}", prepayId));
                paySignReqHandler.SetParameter("signType", "MD5");

                paySign = paySignReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
                package = string.Format("prepay_id={0}", prepayId);
            }
            catch (Exception ex)
            {
                message = "支付过程发生错误";
                LogService.LogWexin("构建支付参数出错", ex.ToString());
            }

            if (!string.IsNullOrEmpty(appId) &&
                !string.IsNullOrEmpty(timeStamp) &&
                !string.IsNullOrEmpty(nonceStr) &&
                !string.IsNullOrEmpty(package) &&
                !string.IsNullOrEmpty(paySign))
            {
                isSuccessFul = true;
            }

            return isSuccessFul;
        }
示例#12
0
        /// <summary>
        /// 查询红包(包括普通红包和裂变红包)
        /// </summary>
        /// <param name="appId">公众账号AppID</param>
        /// <param name="mchId">商户MchID</param>
        /// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
        /// <param name="tenPayCertPath">证书地址(硬盘地址,形如E://cert//apiclient_cert.p12)</param>
        /// <param name="mchBillNo">商家订单号</param>
        /// <returns></returns>
        public static SearchRedPackResult SearchRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath, string mchBillNo)
        {
            string         nonceStr          = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler();

            packageReqHandler.SetParameter("nonce_str", nonceStr);        //随机字符串
            packageReqHandler.SetParameter("appid", appId);               //公众账号ID
            packageReqHandler.SetParameter("mch_id", mchId);              //商户号
            packageReqHandler.SetParameter("mch_billno", mchBillNo);      //填入商家订单号
            packageReqHandler.SetParameter("bill_type", "MCHT");          //MCHT:通过商户订单号获取红包信息。
            string sign = packageReqHandler.CreateMd5Sign("key", tenPayKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名
            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = tenPayCertPath;
            //私钥(在安装证书时设置)
            string password = mchId;

            //调用证书
            //X509Certificate cer = new X509Certificate(cert, password);
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
            string          responseContent = streamReader.ReadToEnd();
            #endregion

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(responseContent);

            SearchRedPackResult searchReturn = new SearchRedPackResult
            {
                err_code     = "",
                err_code_des = ""
            };
            if (doc.SelectSingleNode("/xml/return_code") != null)
            {
                searchReturn.return_code = (doc.SelectSingleNode("/xml/return_code").InnerText.ToUpper() == "SUCCESS");
            }
            if (doc.SelectSingleNode("/xml/return_msg") != null)
            {
                searchReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
            }

            if (searchReturn.return_code == true)
            {
                //redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
                if (doc.SelectSingleNode("/xml/result_code") != null)
                {
                    searchReturn.result_code = (doc.SelectSingleNode("/xml/result_code").InnerText.ToUpper() == "SUCCESS");
                }

                if (searchReturn.result_code == true)
                {
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        searchReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        searchReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/detail_id") != null)
                    {
                        searchReturn.detail_id = doc.SelectSingleNode("/xml/detail_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/status") != null)
                    {
                        searchReturn.status = doc.SelectSingleNode("/xml/status").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/send_type") != null)
                    {
                        searchReturn.send_type = doc.SelectSingleNode("/xml/send_type").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/hb_type") != null)
                    {
                        searchReturn.hb_type = doc.SelectSingleNode("/xml/hb_type").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_num") != null)
                    {
                        searchReturn.total_num = doc.SelectSingleNode("/xml/total_num").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        searchReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/reason") != null)
                    {
                        searchReturn.reason = doc.SelectSingleNode("/xml/reason").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/send_time") != null)
                    {
                        searchReturn.send_time = doc.SelectSingleNode("/xml/send_time").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/refund_time") != null)
                    {
                        searchReturn.refund_time = doc.SelectSingleNode("/xml/refund_time").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/wishing") != null)
                    {
                        searchReturn.wishing = doc.SelectSingleNode("/xml/wishing").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/act_name") != null)
                    {
                        searchReturn.act_name = doc.SelectSingleNode("/xml/act_name").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/hblist") != null)
                    {
                        searchReturn.hblist = new List <RedPackHBInfo>();

                        foreach (XmlNode hbinfo in doc.SelectNodes("/xml/hblist/hbinfo"))
                        {
                            RedPackHBInfo wechatHBInfo = new RedPackHBInfo();
                            wechatHBInfo.openid = hbinfo.SelectSingleNode("openid").InnerText;
                            //wechatHBInfo.status = hbinfo.SelectSingleNode("status").InnerText;
                            wechatHBInfo.amount   = hbinfo.SelectSingleNode("amount").InnerText;
                            wechatHBInfo.rcv_time = hbinfo.SelectSingleNode("rcv_time").InnerText;

                            searchReturn.hblist.Add(wechatHBInfo);
                        }
                    }
                }
                else
                {
                    if (doc.SelectSingleNode("/xml/err_code") != null)
                    {
                        searchReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/err_code_des") != null)
                    {
                        searchReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
                    }
                }
            }

            return(searchReturn);
        }
示例#13
0
文件: wxpay.cs 项目: szoliver/wxpay
        /// <summary>
        /// 获取微信支付签名信息
        /// 调用前请先配置wxPayV3Info属性,否则会支付失败,如果paySign = "ERROR",请查看package内容信息
        /// 目前提供最基本的签名字段,有时间的话可以增加基础以外字段的动态增加,一般情况下,基础的字段也能满足支付需求了
        /// 微信支付步骤:</summary>
        /// 1.$.post调用GetWXPayInfo()获取WXPayModel数据,其中包含签名数据
        /// 2.wxpay.js调用 WeixinJSBridge.invoke('getBrandWCPayRequest')发起微信支付
        /// 3.处理回调,成功后返回success
        /// <param name="payorder"></param>
        /// <param name="openid"></param>
        /// <param name="tfee">支付的金额</param>
        /// <param name="body">备注</param>
        /// <param name="pid">产品信息</param>
        /// <param name="sp_billno">订单号码</param>
        /// <returns>返回签名数据,Response给JS呼出微信支付控件,返回WXPayModel.paySign=ERROR时报错</returns>
        public static WXPayModel GetWXPayInfo(PayOrder payorder, string openid, string tfee, string body, string pid, string sp_billno)
        {
            try
            {
                string timeStamp = "";
                string nonceStr = "";
                string package = "";
                string paySign = "";

                //创建支付应答对象
                RequestHandler packageReqHandler = new RequestHandler(null);
                //初始化
                packageReqHandler.Init();

                //调起微信支付签名
                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", wxPayV3Info.AppId);		  //公众账号ID
                packageReqHandler.SetParameter("mch_id", wxPayV3Info.MchId);		  //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                    //随机字符串
                packageReqHandler.SetParameter("body", body);
                packageReqHandler.SetParameter("out_trade_no", sp_billno);		//商家订单号
                packageReqHandler.SetParameter("spbill_create_ip", HttpContext.Current.Request.UserHostAddress);
                packageReqHandler.SetParameter("total_fee", tfee);
                packageReqHandler.SetParameter("notify_url", wxPayV3Info.TenPayV3Notify);		    //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());	 //交易类型
                packageReqHandler.SetParameter("openid", openid);//OPENID

                //获取package包
                string sign = packageReqHandler.CreateMd5Sign("key", wxPayV3Info.Key);
                packageReqHandler.SetParameter("sign", sign);
                string data = packageReqHandler.ParseXML();
                var result = TenPayV3.Unifiedorder(data);
                var res = XDocument.Parse(result);
                if (res.Element("xml").Element("prepay_id") == null)
                {
                    string err_code = res.Element("xml").Element("return_msg").Value;
                    return new WXPayModel() { paySign = "ERROR", package = err_code };
                }
                string prepayId = res.Element("xml").Element("prepay_id").Value;
                package = string.Format("prepay_id={0}", prepayId);
                //设置支付参数
                RequestHandler paySignReqHandler = new RequestHandler(null);
                paySignReqHandler.SetParameter("appId", wxPayV3Info.AppId);
                paySignReqHandler.SetParameter("timeStamp", timeStamp);
                paySignReqHandler.SetParameter("nonceStr", nonceStr);
                paySignReqHandler.SetParameter("package", package);
                paySignReqHandler.SetParameter("signType", "MD5");
                paySign = paySignReqHandler.CreateMd5Sign("key", wxPayV3Info.Key);
                WXPayModel wm = new WXPayModel()
                {
                    appId = wxPayV3Info.AppId,
                    nonceStr = nonceStr,
                    package = package,
                    payNo = sp_billno,
                    paySign = paySign,
                    timeStamp = timeStamp
                };
                //payorder(wm, openid, tfee, body, pid, param, sp_billno);
                payorder(wm);
                return wm;

            }
            catch (Exception ex)
            {
                return new WXPayModel() { paySign = "ERROR", package = "抛出异常:" + ex.ToString() };
            }
        }
示例#14
0
        /// <summary>
        /// 最新接口调用
        /// 2014-11-24
        /// </summary>
        /// <param name="ttFee">支付金额(单位元)</param>
        /// <param name="busiBody">订单内容</param>
        /// <param name="out_trade_no">订单号</param>
        /// <param name="code"></param>
        protected void WxPayDataV3(decimal ttFee, string busiBody, string out_trade_no, string code)
        {
            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            BLL.wx_userweixin   uwBll    = new BLL.wx_userweixin();
            Model.wx_userweixin uwEntity = uwBll.GetModel(wid);

            // logBll.AddLog(wid,"【微支付】微信预定", "paypage.aspx WxPayDataV3", "211 wid:" + wid, 1);

            //先设置基本信息
            string MchId = paymentInfo.partnerId;       // "1218574001";//

            string partnerKey = paymentInfo.partnerKey; // 商户支付密钥Key。登录微信商户后台,进入栏目【账户设置】【密码安全】【API 安全】【API 密钥】

            string notify_url = "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx";

            logBll.AddLog(wid, "【微支付】微信预定", "paypage.aspx WxPayDataV3", "uwEntity.AppId: " + uwEntity.AppId + "| uwEntity.AppSecret;" + uwEntity.AppSecret + "|code:" + code, 1);


            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";

            string sp_billno = out_trade_no;
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayUtil.BuildRandomStr(28);
            }


            //创建支付应答对象
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //初始化

            //packageReqHandler.SetKey(""/*TenPayV3Info.Key*/);

            timeStamp = TenPayUtil.GetTimestamp();
            nonceStr  = TenPayUtil.GetNoncestr();

            //设置package订单参数
            packageReqHandler.SetParameter("appid", uwEntity.AppId);                      //公众账号ID
            packageReqHandler.SetParameter("mch_id", MchId);                              //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                        //随机字符串
            packageReqHandler.SetParameter("body", busiBody);                             //商品描述
            packageReqHandler.SetParameter("attach", wid + "|" + busiBody);
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                    //商家订单号
            packageReqHandler.SetParameter("total_fee", ((int)(ttFee * 100)).ToString()); //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);  //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", notify_url);                     //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());  //交易类型
            packageReqHandler.SetParameter("openid", openid);                             //用户的openId

            string sign = packageReqHandler.CreateMd5Sign("key", partnerKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;



            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", uwEntity.AppId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", partnerKey);

            packageValue  = "";
            packageValue += " \"appId\": \"" + uwEntity.AppId + "\", ";
            packageValue += " \"timeStamp\": \"" + timeStamp + "\", ";
            packageValue += " \"nonceStr\": \"" + nonceStr + "\", ";
            packageValue += " \"package\": \"" + string.Format("prepay_id={0}", prepayId) + "\", ";
            packageValue += " \"signType\": \"MD5\", ";
            packageValue += " \"paySign\": \"" + paySign + "\"";
        }
示例#15
0
        //public static TenPayInfo TenPayInfo
        //{
        //    get
        //    {
        //        if (_tenPayInfo == null)
        //        {
        //            _tenPayInfo =
        //                TenPayInfoCollection.Data[System.Configuration.ConfigurationManager.AppSettings["WeixinPay_PartnerId"]];
        //        }
        //        return _tenPayInfo;
        //    }
        //}
        /// <summary>
        /// 微信支付:生成请求数据
        /// </summary>
        /// <param name="openid">微信用户id</openid>
        /// <param name="ttFee">商品总价格</param>
        /// <param name="busiBody"></param>
        /// <returns></returns>
        protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no)
        {
            WxPayHelper wxPayHelper = new WxPayHelper();

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            // //先设置基本信息
            // string partnerId = paymentInfo.partnerId;// "1218574001";//
            // string appId = paymentInfo.appId;// "wxa9b8e33e48ac5e0f";//
            // string partnerKey = paymentInfo.partnerKey;// "huyuxianghuyuxianghuyuxiang12345";//
            // //paysignkey(非appkey)
            // string appKey = paymentInfo.paySignKey; //"nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp";//

            // wxPayHelper.SetAppId(appId);
            // wxPayHelper.SetAppKey(appKey);
            // wxPayHelper.SetPartnerKey(partnerKey);
            // wxPayHelper.SetSignType("SHA1");
            // //设置请求package信息
            // wxPayHelper.SetParameter("bank_type", "WX");
            // wxPayHelper.SetParameter("body", busiBody);
            // wxPayHelper.SetParameter("attach",wid+"|"+busiBody);
            // wxPayHelper.SetParameter("partner", partnerId);
            // wxPayHelper.SetParameter("out_trade_no", out_trade_no);
            // wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString());
            // wxPayHelper.SetParameter("fee_type", "1");
            //// wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid);

            // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx");//不能带参数
            // wxPayHelper.SetParameter("spbill_create_ip", MXRequest.GetIP());
            // wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            // //---------有效期截至日期------

            // wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss"));

            // wxPayHelper.SetParameter("input_charset", "UTF-8");
            // packageValue = wxPayHelper.CreateBizPackage();

            ///////////////////////////////////////////////////////////////////////////


            //通过,用code换取access_token
            //var openIdResult = OAuthApi.GetAccessToken(paymentInfo.appId, "a891edd957f2aede546f9256096bf95a", code);
            //if (openIdResult.errcode != ReturnCode.请求成功)
            //{
            //    return Content("错误:" + openIdResult.errmsg);
            //}

            string timeStamp = "";
            string nonceStr  = "";
            string paySign   = "";

            string sp_billno = Request["order_no"];
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            }
            else
            {
                sp_billno = Request["order_no"].ToString();
            }

            //创建支付应答对象
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //初始化
            packageReqHandler.Init();

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

            //设置package订单参数
            packageReqHandler.SetParameter("appid", paymentInfo.appId);                                    //公众账号ID
            packageReqHandler.SetParameter("mch_id", paymentInfo.partnerId);                               //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                                         //随机字符串
            packageReqHandler.SetParameter("body", "aaa");                                                 //商品信息
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                                     //商家订单号
            packageReqHandler.SetParameter("total_fee", "100");                                            //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                   //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", "http://ddd.com");                                //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", Senparc.Weixin.MP.TenPayV3Type.JSAPI.ToString()); //交易类型
            packageReqHandler.SetParameter("openid", "oFo2Hjq6_yMhyz6cQ2MZtmxODOVU");                      //用户的openId

            string sign = packageReqHandler.CreateMd5Sign("key", paymentInfo.partnerKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", paymentInfo.appId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", paymentInfo.partnerKey);

            payaddid        = paymentInfo.appId;
            paytimeStamp    = timeStamp;
            paynonceStr     = nonceStr;
            paypackageValue = packageValue;
            paypaySign      = paySign;
        }
示例#16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            order_type = Request.QueryString["order_type"];
            order_dd   = Request.QueryString["Order_dd"];
            BLL.HG.Hg_list order_T = new BLL.HG.Hg_list();
            if (order_type == "new")
            {
                Model.HG.A_HG_new_order model = order_T.getorder(order_dd);
                string timeStamp = "";
                string nonceStr  = "";
                string paySign   = "";
                //创建支付应答对象
                Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
                //初始化
                packageReqHandler.Init();
                litMoney  = double.Parse(model.total);
                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr  = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", "wx172ece37e2ed2939");                                                                  //公众账号ID
                packageReqHandler.SetParameter("mch_id", "1403543902");                                                                         //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                          //随机字符串
                packageReqHandler.SetParameter("body", model.Name_ + "服务");                                                                     //商品信息
                packageReqHandler.SetParameter("out_trade_no", order_dd);                                                                       //商家订单号
                packageReqHandler.SetParameter("total_fee", ((double.Parse(model.total)) * 100).ToString());                                    //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                                                    //用户的公网ip,不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", MyCommFun.getWebSite() + "/api/wxpay/notify_url.aspx?wid=" + 44 + "|" + order_dd); //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                    //交易类型
                packageReqHandler.SetParameter("openid", model.Openid_);                                                                        //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                packageReqHandler.SetParameter("sign", sign);                       //签名
                string data = packageReqHandler.ParseXML();


                var    result   = TenPayV3.Unifiedorder(data);
                var    res      = XDocument.Parse(result);
                string prepayId = res.Element("xml").Element("prepay_id").Value;

                //设置支付参数
                RequestHandler paySignReqHandler = new RequestHandler(null);
                paySignReqHandler.SetParameter("appId", "wx172ece37e2ed2939");
                paySignReqHandler.SetParameter("timeStamp", timeStamp);
                paySignReqHandler.SetParameter("nonceStr", nonceStr);
                paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
                paySignReqHandler.SetParameter("signType", "MD5");
                paySign         = paySignReqHandler.CreateMd5Sign("key", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                payaddid        = "";
                paytimeStamp    = timeStamp;
                paynonceStr     = nonceStr;
                paypackageValue = string.Format("prepay_id={0}", prepayId);
                paypaySign      = paySign;
                litDate         = DateTime.Now.ToString();
                oreder_name     = model.Name_ + "服务预约";
            }


            else
            {
                hg_number = int.Parse(Request.QueryString["kkl"]);
                Model.HG.HG_order model = order_T.Getorder(order_dd);

                string timeStamp = "";
                string nonceStr  = "";
                string paySign   = "";
                //创建支付应答对象
                Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
                //初始化
                packageReqHandler.Init();
                litMoney  = model.Total;
                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr  = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", "wx172ece37e2ed2939");                                                                  //公众账号ID
                packageReqHandler.SetParameter("mch_id", "1403543902");                                                                         //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                          //随机字符串
                packageReqHandler.SetParameter("body", model.By_name + "护理");                                                                   //商品信息
                packageReqHandler.SetParameter("out_trade_no", order_dd);                                                                       //商家订单号
                packageReqHandler.SetParameter("total_fee", ((model.Total) * 100).ToString());                                                  //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                                                    //用户的公网ip,不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", MyCommFun.getWebSite() + "/api/wxpay/notify_url.aspx?wid=" + 44 + "|" + order_dd); //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                    //交易类型
                packageReqHandler.SetParameter("openid", model.Openid);                                                                         //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                packageReqHandler.SetParameter("sign", sign);                       //签名
                string data = packageReqHandler.ParseXML();


                var    result   = TenPayV3.Unifiedorder(data);
                var    res      = XDocument.Parse(result);
                string prepayId = res.Element("xml").Element("prepay_id").Value;

                //设置支付参数
                RequestHandler paySignReqHandler = new RequestHandler(null);
                paySignReqHandler.SetParameter("appId", "wx172ece37e2ed2939");
                paySignReqHandler.SetParameter("timeStamp", timeStamp);
                paySignReqHandler.SetParameter("nonceStr", nonceStr);
                paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
                paySignReqHandler.SetParameter("signType", "MD5");
                paySign         = paySignReqHandler.CreateMd5Sign("key", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                payaddid        = "";
                paytimeStamp    = timeStamp;
                paynonceStr     = nonceStr;
                paypackageValue = string.Format("prepay_id={0}", prepayId);
                paypaySign      = paySign;
                litDate         = DateTime.Now.ToString();
                oreder_name     = model.By_name + "护理预约";
            }
        }
示例#17
0
        public void ProcessRequest(HttpContext context)
        {
            Model.HG.A_HG_new_order Str = new Model.HG.A_HG_new_order();

            BLL.HG.Hg_list add = new BLL.HG.Hg_list();
            Dictionary <string, string> jsonDict = new Dictionary <string, string>();

            jsonDict = new Dictionary <string, string>();
            string case_ = context.Request.QueryString["case_"];

            if (case_ == "save")
            {
                //  string openid=context.Request.QueryString["openid"];
                string name      = context.Request.QueryString["name"];
                string phone     = context.Request.QueryString["phone"];
                string sex       = context.Request.QueryString["sex"];
                string money     = context.Request.QueryString["money"];
                string type_     = context.Request.QueryString["type_"];
                string time      = context.Request.QueryString["time"];
                string day       = context.Request.QueryString["day"];
                string adress    = context.Request.QueryString["adress"];
                string weixiname = context.Request.QueryString["weixinname"];
                string openid    = context.Request.QueryString["openid"];
                //   string total=context.Request.QueryString["total"];
                //   Str.Openid_ = openid;
                Str.Name_       = name;
                Str.Tel_        = phone;
                Str.Sex_        = sex;
                Str.Pick_many   = money;
                Str.Type_       = type_;
                Str.Time_       = time;
                Str.start_time  = DateTime.Now.ToString();//开始时间
                Str.Pick_day    = day;
                Str.Weixin_name = weixiname;
                Str.Openid_     = openid;
                int day_   = int.Parse(day);
                int money_ = int.Parse(money);
                int total_ = day_ * money_;
                Str.total = total_.ToString();
                string bb = DateTime.Now.Day.ToString() + GuidTo16String();//生成的订单号
                Str.Order_dd   = bb;
                Str.Order_from = "小程序";
                Str.Fw_zt      = "未支付";
                Str.Delet_     = "未删除";
                Str.Adress     = adress;
                int fal = add.Add_order_new(Str);
                //   Str.total = total;
                if (fal == 0)
                {
                    jsonDict.Add("order_dd", bb);
                    jsonDict.Add("errCode", "false");
                    jsonDict.Add("recontent", fal.ToString());
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                }
                else
                {
                    jsonDict.Add("order_dd", bb);
                    jsonDict.Add("errCode", "true");
                    jsonDict.Add("recontent", fal.ToString());
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                }
            }
            else if (case_ == "jujia")
            {
                {
                    //  string openid=context.Request.QueryString["openid"];
                    string name      = context.Request.QueryString["name"];
                    string phone     = context.Request.QueryString["phone"];
                    string sex       = context.Request.QueryString["sex"];
                    string money     = context.Request.QueryString["money"];
                    string type_     = context.Request.QueryString["type_"];
                    string time      = context.Request.QueryString["time"];
                    string day       = context.Request.QueryString["day"];
                    string adress    = context.Request.QueryString["adress"];
                    string weixiname = context.Request.QueryString["weixinname"];
                    string openid    = context.Request.QueryString["openid"];
                    //   string total=context.Request.QueryString["total"];
                    //   Str.Openid_ = openid;
                    Str.Name_       = name;
                    Str.Tel_        = phone;
                    Str.Sex_        = sex;
                    Str.Pick_many   = money;
                    Str.Type_       = type_;
                    Str.Time_       = time;
                    Str.start_time  = DateTime.Now.ToString();//开始时间
                    Str.Pick_day    = day;
                    Str.Weixin_name = weixiname;
                    Str.Openid_     = openid;

                    Str.total = money;
                    string bb = DateTime.Now.Day.ToString() + GuidTo16String();//生成的订单号
                    Str.Order_dd   = bb;
                    Str.Order_from = "小程序";
                    Str.Fw_zt      = "未支付";
                    Str.Delet_     = "未删除";
                    Str.Adress     = adress;
                    int fal = add.Add_order_new(Str);
                    //   Str.total = total;
                    if (fal == 0)
                    {
                        jsonDict.Add("order_dd", bb);
                        jsonDict.Add("errCode", "false");
                        jsonDict.Add("recontent", fal.ToString());
                        context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    }
                    else
                    {
                        jsonDict.Add("order_dd", bb);
                        jsonDict.Add("errCode", "true");
                        jsonDict.Add("recontent", fal.ToString());
                        context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    }
                }
            }
            else if (case_ == "order")
            {
                string openid = context.Request.QueryString["openid"];
                context.Response.ContentType = "text/json";
                context.Response.Write(MyCommFun.GetJsonByDataset(order_new(openid)));
            }
            else
            {
                order_dd = MyCommFun.QueryString("order");
                BLL.HG.Hg_list          order_T = new BLL.HG.Hg_list();
                Model.HG.A_HG_new_order model   = order_T.getorder(order_dd);
                string timeStamp = "";
                string nonceStr  = "";
                string paySign   = "";
                //创建支付应答对象
                Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
                //初始化
                packageReqHandler.Init();

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

                //设置package订单参数
                packageReqHandler.SetParameter("appid", "wx16650bedd9b0916a");                                                                  //公众账号ID
                packageReqHandler.SetParameter("mch_id", "1403543902");                                                                         //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                          //随机字符串
                packageReqHandler.SetParameter("body", model.Name_ + "服务");                                                                     //商品信息
                packageReqHandler.SetParameter("out_trade_no", order_dd);                                                                       //商家订单号
                packageReqHandler.SetParameter("total_fee", ((double.Parse(model.total)) * 100).ToString());                                    //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", context.Request.UserHostAddress);                                            //用户的公网ip,不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", MyCommFun.getWebSite() + "/api/wxpay/notify_url.aspx?wid=" + 44 + "|" + order_dd); //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                    //交易类型
                packageReqHandler.SetParameter("openid", model.Openid_);                                                                        //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                packageReqHandler.SetParameter("sign", sign);                       //签名
                string data = packageReqHandler.ParseXML();


                var      result = TenPayV3.Unifiedorder(data);
                DateTime bb111  = new DateTime();
                WriteTextLog(bb111, result);
                var    res      = XDocument.Parse(result);
                string prepayId = res.Element("xml").Element("prepay_id").Value;

                //设置支付参数
                RequestHandler paySignReqHandler = new RequestHandler(null);
                paySignReqHandler.SetParameter("appId", "wx16650bedd9b0916a");
                paySignReqHandler.SetParameter("timeStamp", timeStamp);
                paySignReqHandler.SetParameter("nonceStr", nonceStr);
                paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
                paySignReqHandler.SetParameter("signType", "MD5");
                paySign         = paySignReqHandler.CreateMd5Sign("key", "70OvzuXGLFP7539B9zbvEMUBd1H1Tv8Q");
                payaddid        = "";
                paytimeStamp    = timeStamp;
                paynonceStr     = nonceStr;
                paypackageValue = string.Format("prepay_id={0}", prepayId);
                paypaySign      = paySign;
                litDate         = DateTime.Now.ToString();
                oreder_name     = model.Name_ + "服务预约";
                context.Response.ContentType = "text/json";
                pay_ bb = new pay_
                {
                    timeStamp = timeStamp,
                    nonceStr  = nonceStr,
                    paySign   = paySign,
                    signType  = "MD5",
                    package   = prepayId
                };
                string json_bill = JsonMapper.ToJson(bb);
                context.Response.Write(json_bill);
            }
        }
示例#18
0
        public ActionResult GetHBInfo(string mchbillno)
        {
            string nonceStr = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		  //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);		  //商户号
            packageReqHandler.SetParameter("mch_billno", mchbillno);                 //填入商家订单号
            packageReqHandler.SetParameter("bill_type", "MCHT");                 //红包发送者名称
            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            packageReqHandler.SetParameter("sign", sign);	                    //签名
            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = @"F:\apiclient_cert.p12";
            //私钥(在安装证书时设置)
            string password = "";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();
            #endregion

            return Content(responseContent);
        }
示例#19
0
 /// <summary>
 /// 获取UI使用的JS支付签名
 /// </summary>
 /// <param name="appId"></param>
 /// <param name="timeStamp"></param>
 /// <param name="nonceStr"></param>
 /// <param name="package">格式:prepay_id={0}</param>
 /// <param name="signType"></param>
 /// <returns></returns>
 public static string GetJsPaySign(string appId, string timeStamp, string nonceStr, string package, string key,
     string signType = "MD5")
 {
     //设置支付参数
     RequestHandler paySignReqHandler = new RequestHandler(null);
     paySignReqHandler.SetParameter("appId", appId);
     paySignReqHandler.SetParameter("timeStamp", timeStamp);
     paySignReqHandler.SetParameter("nonceStr", nonceStr);
     paySignReqHandler.SetParameter("package", package);
     paySignReqHandler.SetParameter("signType", "MD5");
     var paySign = paySignReqHandler.CreateMd5Sign("key", key);
     return paySign;
 }
示例#20
0
        /// <summary>
        /// 查询红包(包括普通红包和裂变红包)
        /// </summary>
        /// <param name="appId">公众账号AppID</param>
        /// <param name="mchId">商户MchID</param>
        /// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
        /// <param name="tenPayCertPath">证书地址(硬盘地址,形如E://cert//apiclient_cert.p12)</param>
        /// <param name="mchBillNo">商家订单号</param>
        /// <returns></returns>
        public static SearchRedPackResult SearchRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath, string mchBillNo)
        {
            string nonceStr = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler();

            packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            packageReqHandler.SetParameter("appid", appId);		  //公众账号ID
            packageReqHandler.SetParameter("mch_id", mchId);		  //商户号
            packageReqHandler.SetParameter("mch_billno", mchBillNo);                 //填入商家订单号
            packageReqHandler.SetParameter("bill_type", "MCHT");                 //MCHT:通过商户订单号获取红包信息。 
            string sign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
            packageReqHandler.SetParameter("sign", sign);	                    //签名
            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = tenPayCertPath;
            //私钥(在安装证书时设置)
            string password = mchId;

            //调用证书
            //X509Certificate cer = new X509Certificate(cert, password);
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();
            #endregion

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(responseContent);

            SearchRedPackResult searchReturn = new SearchRedPackResult
            {
                err_code = "",
                err_code_des = ""
            };
            if (doc.SelectSingleNode("/xml/return_code") != null)
            {
                searchReturn.return_code = (doc.SelectSingleNode("/xml/return_code").InnerText.ToUpper() == "SUCCESS");
            }
            if (doc.SelectSingleNode("/xml/return_msg") != null)
            {
                searchReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
            }

            if (searchReturn.return_code == true)
            {
                //redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
                if (doc.SelectSingleNode("/xml/result_code") != null)
                {
                    searchReturn.result_code = (doc.SelectSingleNode("/xml/result_code").InnerText.ToUpper() == "SUCCESS");
                }

                if (searchReturn.result_code == true)
                {
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        searchReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        searchReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/detail_id") != null)
                    {
                        searchReturn.detail_id = doc.SelectSingleNode("/xml/detail_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/status") != null)
                    {
                        searchReturn.status = doc.SelectSingleNode("/xml/status").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/send_type") != null)
                    {
                        searchReturn.send_type = doc.SelectSingleNode("/xml/send_type").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/hb_type") != null)
                    {
                        searchReturn.hb_type = doc.SelectSingleNode("/xml/hb_type").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_num") != null)
                    {
                        searchReturn.total_num = doc.SelectSingleNode("/xml/total_num").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        searchReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/reason") != null)
                    {
                        searchReturn.reason = doc.SelectSingleNode("/xml/reason").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/send_time") != null)
                    {
                        searchReturn.send_time = doc.SelectSingleNode("/xml/send_time").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/refund_time") != null)
                    {
                        searchReturn.refund_time = doc.SelectSingleNode("/xml/refund_time").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/wishing") != null)
                    {
                        searchReturn.wishing = doc.SelectSingleNode("/xml/wishing").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/act_name") != null)
                    {
                        searchReturn.act_name = doc.SelectSingleNode("/xml/act_name").InnerText;
                    }

                    if (doc.SelectSingleNode("/xml/hblist") != null)
                    {
                        searchReturn.hblist = new List<RedPackHBInfo>();

                        foreach (XmlNode hbinfo in doc.SelectNodes("/xml/hblist/hbinfo"))
                        {
                            RedPackHBInfo wechatHBInfo = new RedPackHBInfo();
                            wechatHBInfo.openid = hbinfo.SelectSingleNode("openid").InnerText;
                            //wechatHBInfo.status = hbinfo.SelectSingleNode("status").InnerText;
                            wechatHBInfo.amount = hbinfo.SelectSingleNode("amount").InnerText;
                            wechatHBInfo.rcv_time = hbinfo.SelectSingleNode("rcv_time").InnerText;

                            searchReturn.hblist.Add(wechatHBInfo);
                        }
                    }
                }
                else
                {
                    if (doc.SelectSingleNode("/xml/err_code") != null)
                    {
                        searchReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/err_code_des") != null)
                    {
                        searchReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
                    }
                }
            }

            return searchReturn;
        }
示例#21
0
        public ActionResult JsApi(string code, string state)
        {
            if (string.IsNullOrEmpty(code))
            {
                return Content("您拒绝了授权!");
            }

            if (!state.Contains("|"))
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return Content("验证失败!请从正规途径进入!1001");
            }

            //获取产品信息
            var stateData = state.Split('|');
            int productId = 0;
            ProductModel product = null;
            if (int.TryParse(stateData[0], out productId))
            {
                int hc = 0;
                if (int.TryParse(stateData[1], out hc))
                {
                    var products = ProductModel.GetFakeProductList();
                    product = products.FirstOrDefault(z => z.Id == productId);
                    if (product == null || product.GetHashCode() != hc)
                    {
                        return Content("商品信息不存在,或非法进入!1002");
                    }
                    ViewData["product"] = product;
                }
            }

            //通过,用code换取access_token
            var openIdResult = OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code);
            if (openIdResult.errcode != ReturnCode.请求成功)
            {
                return Content("错误:" + openIdResult.errmsg);
            }

            string timeStamp = "";
            string nonceStr = "";
            string paySign = "";

            string sp_billno = Request["order_no"];
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            }
            else
            {
                sp_billno = Request["order_no"].ToString();
            }

            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);
            //初始化
            packageReqHandler.Init();

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

            //设置package订单参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		  //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);		  //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                    //随机字符串
            packageReqHandler.SetParameter("body", product == null ? "test" : product.Name);    //商品信息
            packageReqHandler.SetParameter("out_trade_no", sp_billno);		//商家订单号
            packageReqHandler.SetParameter("total_fee", product == null ? "100" : (product.Price * 100).ToString());			        //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);   //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);		    //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());	                    //交易类型
            packageReqHandler.SetParameter("openid", openIdResult.openid);	                    //用户的openId

            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            packageReqHandler.SetParameter("sign", sign);	                    //签名

            string data = packageReqHandler.ParseXML();

            var result = TenPayV3.Unifiedorder(data);
            var res = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            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}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);

            ViewData["appId"] = TenPayV3Info.AppId;
            ViewData["timeStamp"] = timeStamp;
            ViewData["nonceStr"] = nonceStr;
            ViewData["package"] = string.Format("prepay_id={0}", prepayId);
            ViewData["paySign"] = paySign;

            return View();
        }
        /// <summary>
        /// 微信支付接口
        /// </summary>
        /// <param name="productName">产品名称</param>
        /// <param name="orderId">订单号</param>
        /// <param name="amount">金额</param>
        /// <param name="createIp">用户IP</param>
        /// <param name="openId">用户OpenId</param>
        /// <returns>prepay_id:微信生成的预支付回话标识,用于后续接口调用中使用,该值有效期为2小时; </returns>
        public static string Unifiedorder(string productName, long orderId, decimal amount, string createIp,string openId)
        {
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);

            var nonceStr = TenPayV3Util.GetNoncestr();

            //创建请求统一订单接口参数
            packageReqHandler.SetParameter("appid", AppId);
            packageReqHandler.SetParameter("mch_id", Mchid);
            packageReqHandler.SetParameter("nonce_str", nonceStr);
            packageReqHandler.SetParameter("body", productName);
            packageReqHandler.SetParameter("out_trade_no", orderId.ToString());
            packageReqHandler.SetParameter("total_fee", Convert.ToInt32(amount * 100).ToString());
            packageReqHandler.SetParameter("spbill_create_ip", createIp);
            packageReqHandler.SetParameter("notify_url", NotifyUrl);
            packageReqHandler.SetParameter("trade_type", "JSAPI");
            packageReqHandler.SetParameter("openid", openId);
            string sign = packageReqHandler.CreateMd5Sign("key", PayKey);
            packageReqHandler.SetParameter("sign", sign);

            string data = packageReqHandler.ParseXML();
            logger.Info("统一订单接口请求信息:" + data);
            //证书相关
            var cert = new X509Certificate2(SSLCERT_PATH, SSLCERT_PASSWORD);
              try
            {
                //调用统一订单接口
                var result = TenPayV3.Unifiedorder(data, cert);
                logger.Info("统一订单接口返回信息:"+result);
                var unifiedorderRes = XDocument.Parse(result);
                string return_code = unifiedorderRes.Element("xml").Element("return_code").Value;
                string result_code =unifiedorderRes.Element("xml").Element("result_code").Value;
                if (return_code == "SUCCESS" && result_code == "SUCCESS")
                    return unifiedorderRes.Element("xml").Element("prepay_id").Value;
                else
                    return "FAIL";
            }
            catch (Exception e)
            {
                logger.Error(e);
                return "ERROR";
            }
        }
示例#23
0
        /*
         * 错误码	描述	解决方案
         * NO_AUTH	发放失败,此请求可能存在风险,已被微信拦截	请提醒用户检查自身帐号是否异常。使用常用的活跃的微信号可避免这种情况。
         * SENDNUM_LIMIT	该用户今日领取红包个数超过限制	如有需要、请在微信支付商户平台【api安全】中重新配置 【每日同一用户领取本商户红包不允许超过的个数】。
         * CA_ERROR	请求未携带证书,或请求携带的证书出错	到商户平台下载证书,请求带上证书后重试。
         * ILLEGAL_APPID	错误传入了app的appid	接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的)。
         * SIGN_ERROR	商户签名错误	按文档要求重新生成签名后再重试。
         * FREQ_LIMIT	受频率限制	请对请求做频率控制
         * XML_ERROR	请求的xml格式错误,或者post的数据为空	检查请求串,确认无误后重试
         * PARAM_ERROR	参数错误	请查看err_code_des,修改设置错误的参数
         * OPENID_ERROR	Openid错误	根据用户在商家公众账号上的openid,获取用户在红包公众账号上的openid 错误。请核对商户自身公众号appid和用户在此公众号下的openid。
         * NOTENOUGH	余额不足	商户账号余额不足,请登录微信支付商户平台充值
         * FATAL_ERROR	重复请求时,参数与原单不一致	使用相同商户单号进行重复请求时,参数与第一次请求时不一致,请检查并修改参数后再重试。
         * SECOND_OVER_LIMITED	企业红包的按分钟发放受限	每分钟发送红包数量不得超过1800个;(可联系微信支付[email protected]调高额度)
         * DAY_ OVER_LIMITED	企业红包的按天日发放受限	单个商户日发送红包数量不大于10000个;(可联系微信支付[email protected]调高额度)
         * MONEY_LIMIT	红包金额发放限制	每个红包金额必须大于1元,小于1000元(可联系微信支付[email protected]调高额度至4999元)
         * SEND_FAILED	红包发放失败,请更换单号再重试	原商户单号已经失败,如果还要对同一个用户发放红包, 需要更换新的商户单号再试。
         * SYSTEMERROR	系统繁忙,请再试。	可用同一商户单号再次调用,只会发放一个红包
         * PROCESSING	请求已受理,请稍后使用原单号查询发放结果	二十分钟后查询,按照查询结果成功失败进行处理
         */

        #endregion

        /// <summary>
        /// 普通红包发送
        /// </summary>
        /// <param name="appId">公众账号AppID</param>
        /// <param name="mchId">商户MchID</param>
        /// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
        /// <param name="tenPayCertPath">证书地址(硬盘物理地址,形如E:\\cert\\apiclient_cert.p12)</param>
        /// <param name="openId">要发红包的用户的OpenID</param>
        /// <param name="senderName">红包发送者名称,会显示给接收红包的用户</param>
        /// <param name="iP">发送红包的服务器地址</param>
        /// <param name="redPackAmount">红包金额(单位分)</param>
        /// <param name="wishingWord">祝福语</param>
        /// <param name="actionName">活动名称</param>
        /// <param name="remark">活动描述,用于低版本微信显示</param>
        /// <param name="nonceStr">将nonceStr随机字符串返回,开发者可以存到数据库用于校验</param>
        /// <param name="paySign">将支付签名返回,开发者可以存到数据库用于校验</param>
        /// <param name="mchBillNo">商户订单号,新的订单号可以从RedPackApi.GetNewBillNo(mchId)方法获得,如果传入null,则系统自动生成</param>
        /// <param name="scene">场景id(非必填)</param>
        /// <param name="riskInfo">活动信息(非必填),String(128)posttime:用户操作的时间戳。
        /// <para>示例:posttime%3d123123412%26clientversion%3d234134%26mobile%3d122344545%26deviceid%3dIOS</para>
        /// <para>mobile:业务系统账号的手机号,国家代码-手机号。不需要+号</para>
        /// <para>deviceid :mac 地址或者设备唯一标识</para>
        /// <para>clientversion :用户操作的客户端版本</para>
        /// <para>把值为非空的信息用key = value进行拼接,再进行urlencode</para>
        /// <para>urlencode(posttime= xx & mobile = xx & deviceid = xx)</para>
        /// </param>
        /// <param name="consumeMchId">资金授权商户号,服务商替特约商户发放时使用(非必填),String(32)。示例:1222000096</param>
        /// <returns></returns>
        public static NormalRedPackResult SendNormalRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath,
                                                            string openId, string senderName,
                                                            string iP, int redPackAmount, string wishingWord, string actionName, string remark,
                                                            out string nonceStr, out string paySign,
                                                            string mchBillNo, RedPack_Scene?scene = null, string riskInfo = null, string consumeMchId = null)
        {
            mchBillNo = mchBillNo ?? GetNewBillNo(mchId);

            nonceStr = TenPayV3Util.GetNoncestr();
            //RequestHandler packageReqHandler = new RequestHandler(null);

            //string accessToken = AccessTokenContainer.GetAccessToken(ConstantClass.AppID);
            //UserInfoJson userInforResult = UserApi.Info(accessToken, openID);

            RequestHandler packageReqHandler = new RequestHandler();

            //设置package订单参数
            packageReqHandler.SetParameter("nonce_str", nonceStr);                    //随机字符串
            packageReqHandler.SetParameter("wxappid", appId);                         //公众账号ID
            packageReqHandler.SetParameter("mch_id", mchId);                          //商户号
            packageReqHandler.SetParameter("mch_billno", mchBillNo);                  //填入商家订单号
            packageReqHandler.SetParameter("send_name", senderName);                  //红包发送者名称
            packageReqHandler.SetParameter("re_openid", openId);                      //接受收红包的用户的openId
            packageReqHandler.SetParameter("total_amount", redPackAmount.ToString()); //付款金额,单位分
            packageReqHandler.SetParameter("total_num", "1");                         //红包发放总人数
            packageReqHandler.SetParameter("wishing", wishingWord);                   //红包祝福语
            packageReqHandler.SetParameter("client_ip", iP);                          //调用接口的机器Ip地址
            packageReqHandler.SetParameter("act_name", actionName);                   //活动名称
            packageReqHandler.SetParameter("remark", remark);                         //备注信息

            if (scene.HasValue)
            {
                packageReqHandler.SetParameter("scene_id", scene.Value.ToString());//场景id
            }
            if (riskInfo != null)
            {
                packageReqHandler.SetParameter("risk_info", riskInfo);//活动信息
            }
            if (consumeMchId != null)
            {
                packageReqHandler.SetParameter("consume_mch_id", consumeMchId);//活动信息
            }

            paySign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
            packageReqHandler.SetParameter("sign", paySign);                        //签名


            //最新的官方文档中将以下三个字段去除了
            //packageReqHandler.SetParameter("nick_name", "提供方名称");                 //提供方名称
            //packageReqHandler.SetParameter("max_value", "100");                //最大红包金额,单位分
            //packageReqHandler.SetParameter("min_value", "100");                //最小红包金额,单位分

            //发红包需要post的数据
            string data = packageReqHandler.ParseXML();

            //发红包接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = tenPayCertPath;
            //私钥(在安装证书时设置)
            string password = mchId;

            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //X509Certificate cer = new X509Certificate(cert, password);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";


            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
            string          responseContent = streamReader.ReadToEnd();
            #endregion

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(responseContent);

            //XDocument xDoc = XDocument.Load(responseContent);

            NormalRedPackResult normalReturn = new NormalRedPackResult
            {
                err_code     = "",
                err_code_des = ""
            };

            if (doc.SelectSingleNode("/xml/return_code") != null)
            {
                normalReturn.return_code = doc.SelectSingleNode("/xml/return_code").InnerText;
            }
            if (doc.SelectSingleNode("/xml/return_msg") != null)
            {
                normalReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
            }

            if (normalReturn.ReturnCodeSuccess)
            {
                //redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
                if (doc.SelectSingleNode("/xml/result_code") != null)
                {
                    normalReturn.result_code = doc.SelectSingleNode("/xml/result_code").InnerText;
                }

                if (normalReturn.ResultCodeSuccess)
                {
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }

                    //裂变红包才有
                    if (doc.SelectSingleNode("/xml/send_time") != null)
                    {
                        normalReturn.send_time = doc.SelectSingleNode("/xml/send_time").InnerText;
                    }
                    //裂变红包才有
                    if (doc.SelectSingleNode("/xml/send_listid") != null)
                    {
                        normalReturn.send_listid = doc.SelectSingleNode("/xml/send_listid").InnerText;
                    }
                }
                else
                {
                    if (doc.SelectSingleNode("/xml/err_code") != null)
                    {
                        normalReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/err_code_des") != null)
                    {
                        normalReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_billno") != null)
                    {
                        normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/mch_id") != null)
                    {
                        normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/wxappid") != null)
                    {
                        normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/re_openid") != null)
                    {
                        normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
                    }
                    if (doc.SelectSingleNode("/xml/total_amount") != null)
                    {
                        normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
                    }
                }
            }

            return(normalReturn);
        }
示例#24
0
        /// <summary>
        /// 提现转账
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="money"></param>
        /// <param name="openId"></param>
        /// <param name="checkName">【NO_CHECK:不校验真实姓名 FORCE_CHECK:强校验真实姓 OPTION_CHECK:针对已实名认证的用户才校验真实姓名】</param>
        /// <param name="reUserName"></param>
        /// <param name="spbillCreateIp"></param>
        /// <param name="desc"></param>
        /// <param name="nonceStr"></param>
        public void WithdrawMoney(string orderId, decimal money, string openId, string checkName, string reUserName,
                                  string spbillCreateIp, string desc,
                                  string nonceStr = null)
        {
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);

            //初始化
            packageReqHandler.Init();

            nonceStr = string.IsNullOrEmpty(nonceStr) ? TenPayUtil.GetNoncestr() : nonceStr;

            //设置package订单参数
            packageReqHandler.SetParameter("mch_appid", AppId);                    //公众账号ID
            packageReqHandler.SetParameter("mchid", MchId);                        //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                 //随机字符串
            packageReqHandler.SetParameter("desc", desc);                          //企业付款描述信息
            packageReqHandler.SetParameter("check_name", checkName);               //校验用户姓名选项
            packageReqHandler.SetParameter("re_user_name", reUserName);            //收款用户姓名
            packageReqHandler.SetParameter("partner_trade_no", orderId);           //商户订单号
            packageReqHandler.SetParameter("amount", (money * 100).ToString("0")); //转账金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", spbillCreateIp);    //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("openid", openId);                      //用户的openId
            string sign = packageReqHandler.CreateMd5Sign("key", Key);

            packageReqHandler.SetParameter("sign", sign); //签名
            string data = packageReqHandler.ParseXML();

            #region transfers()

            //发企业支付接口地址
            string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            //string cert = @"D:\apiclient_cert.p12";
            //私钥(在安装证书时设置)
            string password = MchId;
            ServicePointManager.ServerCertificateValidationCallback =
                new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            //X509Certificate2 cer = new X509Certificate2(cert, password,
            //    X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);


            X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            certStore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certCollection = certStore.Certificates.Find(
                X509FindType.FindByThumbprint, "9595BAC7475049BA7CB06ACD6CDC792BADF40217", false);

            X509Certificate2 cert = null;
            if (certCollection.Count > 0)
            {
                cert = certCollection[0];
            }

            #region 发起post请求

            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cert);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
            string          result          = streamReader.ReadToEnd();

            #endregion

            #endregion

            var res = XDocument.Parse(result);

            if (res.Element("xml") == null)
            {
                throw new Exception("转账订单接口出错");
            }

            var returnCode = res.Element("xml").Element("return_code") == null
                ? null
                : res.Element("xml").Element("return_code").Value;
            var resultCode = res.Element("xml").Element("result_code") == null
                ? null
                : res.Element("xml").Element("result_code").Value;
            if (string.IsNullOrEmpty(returnCode))
            {
                throw new Exception("转账订单接口出错,未获取到返回状态码");
            }
            if (returnCode == "FAIL" || resultCode == "FAIL")
            {
                var returnMsg = res.Element("xml").Element("return_msg").ToString();
                throw new Exception(returnMsg);
            }
        }
        /// <summary>
        /// 企业支付
        /// </summary>
        /// <param name="openId">openId</param>
        /// <param name="payCode">支付ID,订单号+支付日志ID</param>
        /// <param name="amount">金额</param>
        /// <param name="desc">付款描述信息</param>
        /// <returns></returns>
        public static string QYPay(string openId,string payCode,decimal amount,string desc)
        {
            var payStatus = 1;
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);
            var nonceStr = TenPayV3Util.GetNoncestr();

            //创建请求接口参数
            packageReqHandler.SetParameter("mch_appid", AppId);
            packageReqHandler.SetParameter("mchid", Mchid);
            packageReqHandler.SetParameter("nonce_str", nonceStr);
            packageReqHandler.SetParameter("partner_trade_no", payCode);
            packageReqHandler.SetParameter("openid", openId);
            packageReqHandler.SetParameter("check_name", "NO_CHECK");//不校验用户姓名
            packageReqHandler.SetParameter("desc", desc);
            packageReqHandler.SetParameter("amount", Convert.ToInt32(amount * 100).ToString());
            packageReqHandler.SetParameter("spbill_create_ip", IP );
            string sign = packageReqHandler.CreateMd5Sign("key", PayKey);
            packageReqHandler.SetParameter("sign", sign);

            string data = packageReqHandler.ParseXML();

            //证书相关
            var cert = new X509Certificate2(SSLCERT_PATH, SSLCERT_PASSWORD);
            var access = new WeixinPayLogDataAccess();
            var weixinService = new WeiXinService(access);
            try
            {
                //调用企业支付接口
                var result = TenPayV3.QYPay(data, cert);
                logger.Info("企业支付返回信息:"+result);
                var unifiedorderRes = XDocument.Parse(result);
                string return_code = unifiedorderRes.Element("xml").Element("return_code").Value;
                if(return_code=="SUCCESS")
                {
                    payStatus = 1;
                }
                else
                {
                    payStatus = 0;
                }

                return return_code;
            }
            catch (Exception e)
            {
                logger.Error(e);
                //payStatus = 0;
                //var paylog = new WeixinPayLog()
                //{
                //    OrderId = orderId,
                //    WxOpenId = openId,
                //    Description = desc,
                //    Amount = amount,
                //    Status = payStatus,
                //    CreateTime = DateTime.Now
                //};
                //weixinService.InsertWeixinPayLog(paylog);
                return "ERROR";
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="mchId"></param>
        /// <param name="body"></param>
        /// <param name="outTradeNo"></param>
        /// <param name="totalFee"></param>
        /// <param name="spbillCreateIp"></param>
        /// <param name="notifyUrl"></param>
        /// <param name="tradeType"></param>
        /// <param name="openid"></param>
        /// <param name="key"></param>
        /// <param name="nonceStr"></param>
        public TenPayV3UnifiedorderRequestData(string appId, string mchId, string body, string outTradeNo, decimal totalFee, string spbillCreateIp, string notifyUrl, TenPayV3Type tradeType, string openid, string key, string nonceStr)
        {
            AppId = appId;
            MchId = mchId;
            NonceStr = nonceStr;
            Body = body ?? "Senparc TenpayV3";
            OutTradeNo = outTradeNo;
            TotalFee = totalFee;
            SpbillCreateIP = spbillCreateIp;
            NotifyUrl = notifyUrl;
            TradeType = tradeType;
            OpenId = openid;
            Key = key;

            #region 设置RequestHandler

            //创建支付应答对象
            PackageRequestHandler = new RequestHandler(null);
            //初始化
            PackageRequestHandler.Init();

            //设置package订单参数
            PackageRequestHandler.SetParameter("appid", this.AppId);          //公众账号ID
            PackageRequestHandler.SetParameter("mch_id", this.MchId);         //商户号
            PackageRequestHandler.SetParameter("nonce_str", this.NonceStr);                    //随机字符串
            PackageRequestHandler.SetParameter("body", this.Body);    //商品信息
            PackageRequestHandler.SetParameter("out_trade_no", this.OutTradeNo);      //商家订单号
            PackageRequestHandler.SetParameter("total_fee", this.TotalFee.ToString());                    //商品金额,以分为单位(money * 100).ToString()
            PackageRequestHandler.SetParameter("spbill_create_ip", this.SpbillCreateIP);   //用户的公网ip,不是商户服务器IP
            PackageRequestHandler.SetParameter("notify_url", this.NotifyUrl);          //接收财付通通知的URL
            PackageRequestHandler.SetParameter("trade_type", this.TradeType.ToString());                        //交易类型
            PackageRequestHandler.SetParameter("openid", this.OpenId);                      //用户的openId
            Sign = PackageRequestHandler.CreateMd5Sign("key", this.Key);
            PackageRequestHandler.SetParameter("sign", Sign);                       //签名
            #endregion
        }
示例#27
0
        /// <summary>
        /// 原生支付 模式二
        /// 根据统一订单返回的code_url生成支付二维码。该模式链接较短,生成的二维码打印到结账小票上的识别率较高。
        /// 注意:code_url有效期为2小时,过期后扫码不能再发起支付
        /// </summary>
        /// <returns></returns>
        public ActionResult NativeByCodeUrl()
        {
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);

            var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            var nonceStr = TenPayV3Util.GetNoncestr();

            //商品Id,用户自行定义
            string productId = DateTime.Now.ToString("yyyyMMddHHmmss");

            //创建请求统一订单接口参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);
            packageReqHandler.SetParameter("nonce_str", nonceStr);
            packageReqHandler.SetParameter("body", "test");
            packageReqHandler.SetParameter("out_trade_no", sp_billno);
            packageReqHandler.SetParameter("total_fee", "1");
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);
            packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString());
            packageReqHandler.SetParameter("product_id", productId);

            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            packageReqHandler.SetParameter("sign", sign);

            string data = packageReqHandler.ParseXML();

            //调用统一订单接口
            var result = TenPayV3.Unifiedorder(data);
            var unifiedorderRes = XDocument.Parse(result);
            string codeUrl = unifiedorderRes.Element("xml").Element("code_url").Value;

            BitMatrix bitMatrix;
            bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 600, 600);
            BarcodeWriter bw = new BarcodeWriter();

            var ms = new MemoryStream();
            var bitmap = bw.Write(bitMatrix);
            bitmap.Save(ms, ImageFormat.Png);
            //return File(ms, "image/png");
            ms.WriteTo(Response.OutputStream);
            Response.ContentType = "image/png";
            return null;
        }
示例#28
0
        /// <summary>
        /// 退款申请接口
        /// </summary>
        /// <returns></returns>
        public ActionResult Refund()
        {
            string nonceStr = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		  //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);		  //商户号
            packageReqHandler.SetParameter("out_trade_no", "");                 //填入商家订单号
            packageReqHandler.SetParameter("out_refund_no", "");                //填入退款订单号
            packageReqHandler.SetParameter("total_fee", "");               //填入总金额
            packageReqHandler.SetParameter("refund_fee", "");               //填入退款金额
            packageReqHandler.SetParameter("op_user_id", TenPayV3Info.MchId);   //操作员Id,默认就是商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            packageReqHandler.SetParameter("sign", sign);	                    //签名
            //退款需要post的数据
            string data = packageReqHandler.ParseXML();

            //退款接口地址
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = @"F:\apiclient_cert.p12";
            //私钥(在安装证书时设置)
            string password = "";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();
            #endregion

            var res = XDocument.Parse(responseContent);
            string openid = res.Element("xml").Element("out_refund_no").Value;

            return Content(openid);
        }
示例#29
0
        /// <summary>
        /// 支付页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Pay(long? orderId,string act="pay")
        {
            try
            {
                var orderPayViewModel = new OrderPayViewModel();
                orderPayViewModel.Action = act;
                
                if (orderId.HasValue)
                {
                    var orderModel = OrderService.GetOrder(this.UserInfo.UserId, orderId.Value);

                    if (orderModel != null)
                    {
                        var productModel = ProductService.GetProductById(orderModel.ProductId);

                        if (productModel != null)
                        {
                            orderPayViewModel.Name = productModel.Name;
                            orderPayViewModel.SheepType = productModel.SheepType;
                            orderPayViewModel.OrderId = orderId.Value;
                            orderPayViewModel.Price = productModel.Price;
                            orderPayViewModel.Count = orderModel.ProductCount;
                            orderPayViewModel.TotalPrice = productModel.Price * orderModel.ProductCount;
                            orderPayViewModel.StartTime = productModel.StartTime;
                            orderPayViewModel.EndTime = productModel.EndTime;
                            orderPayViewModel.ImgUrl = productModel.ImgUrl;
                            orderPayViewModel.PayType = orderModel.PayType;
                            if (act.ToLower() == "redeem")
                            {
                                orderPayViewModel.Action = "redeem";
                                orderPayViewModel.Principal = orderPayViewModel.TotalPrice;
                                orderPayViewModel.Earing = productModel.Earning*orderPayViewModel.Count;
                            }
                            else if (act.ToLower() == "pay")
                            {
                                if (!productModel.CanSale)
                                {
                                    return RedirectToAction("OrderList", "Home", new { tab = 3 });
                                }
                                orderPayViewModel.Action = "pay";
                                #region 微信支付



                                var userid = this.UserInfo.UserId;
                                var openId = this.UserInfo.WxOpenId;
                                var order = OrderService.GetOrderViewModel(userid, orderId.Value);
                                if (string.IsNullOrEmpty(order.ProductName) || order.OrderId == 0 || order.TotalMoney == 0M)
                                {
                                    return Content("ERROR");
                                }
                                var timeStamp = TenPayV3Util.GetTimestamp();
                                var nonceStr = TenPayV3Util.GetNoncestr();

                                var pre_id = WeixinPay.WeixinPayApi.Unifiedorder(order.ProductName, order.OrderId, order.TotalMoney, Request.UserHostAddress, openId);
                                if (pre_id == "ERROR" || pre_id == "FAIL")
                                    return Content("ERROR");
                                var package = "prepay_id=" + pre_id;

                                var req = new RequestHandler(null);
                                req.SetParameter("appId", AppId);
                                req.SetParameter("timeStamp", timeStamp);
                                req.SetParameter("nonceStr", nonceStr);
                                req.SetParameter("package", package);
                                req.SetParameter("signType", "MD5");
                                var paySign = req.CreateMd5Sign("key", PayKey);

                                //绑定页面数据
                                ViewBag.TimeStamp = timeStamp;
                                ViewBag.NonceStr = nonceStr;
                                ViewBag.PaySign = paySign;
                                ViewBag.Package = package;
                                ViewBag.AppId = AppId;
                                ViewBag.OrderId = order.OrderId;
                                ViewBag.Uid =
                                    DotNet.Common.CryptographyHelper.Base64Encrypt(this.UserInfo.UserId.ToString());
                                OrderService.InsertOrderPay(new OrderPayModel()
                                {
                                    PayId = pre_id,
                                    OrdeId = order.OrderId,
                                    UserId = order.UserId,
                                    Status = 0,
                                    CreateTime = DateTime.Now
                                });

                                #endregion
                            }
                        }

                        
                    }
                }
                return View(orderPayViewModel);

            
            }
            catch (Exception e)
            {
                logger.Error(e);
                throw;
            }
           

        }
示例#30
0
        public ActionResult SubmitPreSaleOrder(PreSaleOrderViewModel preSaleOrderViewModel)
        {
            var jsonResult=new JsonResult();
            if (!string.IsNullOrEmpty(preSaleOrderViewModel.InviteCode))
            {
                preSaleOrderViewModel.InviteCode = preSaleOrderViewModel.InviteCode.Replace(" ", "");
            }
            var preSaleOrder = new PreSaleOrder
            {
                OrderId = preSaleOrderViewModel.OrderId,//OrderService.GetNewOrderId(),
                UserId = this.UserInfo.UserId,
                ProductId = preSaleOrderViewModel.PreSaleProduct.ProductId,
                Price = preSaleOrderViewModel.PreSaleProduct.Price,
                Count = preSaleOrderViewModel.Count,
                ProvinceId = preSaleOrderViewModel.ProvinceId,
                CityId = preSaleOrderViewModel.CityId,
                Code = preSaleOrderViewModel.AreaId,
                Address = preSaleOrderViewModel.Address,
                Status = 0,
                CreateTime = DateTime.Now,
                Receiver = preSaleOrderViewModel.UserName,
                Phone=preSaleOrderViewModel.Phone,
                TotalMoney = preSaleOrderViewModel.Count* preSaleOrderViewModel.PreSaleProduct.Price,
                ExpressDelivery = string.Empty,
                InviteCode = preSaleOrderViewModel.InviteCode
            };

            

            var result=PreSaleOrderService.SubmitPreSaleOrder(preSaleOrder);

            if (result > 0)
            {
                #region 微信支付所需数据计算
                var timeStamp = TenPayV3Util.GetTimestamp();
                var nonceStr = TenPayV3Util.GetNoncestr();
                var openId = this.UserInfo.WxOpenId;
                var pre_id = WeixinPay.WeixinPayApi.Unifiedorder(preSaleOrderViewModel.PreSaleProduct.Name,
                    preSaleOrder.OrderId, preSaleOrder.Price* preSaleOrder.Count, Request.UserHostAddress, openId);
                if (pre_id == "ERROR" || pre_id == "FAIL")
                    return Content("ERROR");
                var package = "prepay_id=" + pre_id;

                var req = new RequestHandler(null);
                req.SetParameter("appId", AppId);
                req.SetParameter("timeStamp", timeStamp);
                req.SetParameter("nonceStr", nonceStr);
                req.SetParameter("package", package);
                req.SetParameter("signType", "MD5");
                var paySign = req.CreateMd5Sign("key", PayKey);


                #endregion

                preSaleOrderViewModel.NonceStr = nonceStr;
                preSaleOrderViewModel.TimeStamp = timeStamp;
                preSaleOrderViewModel.Package = package;
                preSaleOrderViewModel.AppId = AppId;
                preSaleOrderViewModel.PaySign = paySign;
            }
            else
            {
                preSaleOrderViewModel.OrderId = 0;
            }

            jsonResult.Data = preSaleOrderViewModel;
            return jsonResult;
        }
示例#31
0
        /// <summary>
        /// 原生支付 模式一
        /// </summary>
        /// <returns></returns>
        public ActionResult Native()
        {
            RequestHandler nativeHandler = new RequestHandler(null);
            string timeStamp = TenPayV3Util.GetTimestamp();
            string nonceStr = TenPayV3Util.GetNoncestr();

            //商品Id,用户自行定义
            string productId = DateTime.Now.ToString("yyyyMMddHHmmss");

            nativeHandler.SetParameter("appid", TenPayV3Info.AppId);
            nativeHandler.SetParameter("mch_id", TenPayV3Info.MchId);
            nativeHandler.SetParameter("time_stamp", timeStamp);
            nativeHandler.SetParameter("nonce_str", nonceStr);
            nativeHandler.SetParameter("product_id", productId);
            string sign = nativeHandler.CreateMd5Sign("key", TenPayV3Info.Key);

            var url = TenPayV3.NativePay(TenPayV3Info.AppId, timeStamp, TenPayV3Info.MchId, nonceStr, productId, sign);

            BitMatrix bitMatrix;
            bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 600, 600);
            BarcodeWriter bw = new BarcodeWriter();

            var ms = new MemoryStream();
            var bitmap = bw.Write(bitMatrix);
            bitmap.Save(ms, ImageFormat.Png);
            //return File(ms, "image/png");
            ms.WriteTo(Response.OutputStream);
            Response.ContentType = "image/png";
            return null;
        }
示例#32
0
        /// <summary>
        /// 按订单号进行支付
        /// </summary>
        /// <param name="orderid">订单号</param>
        /// <returns></returns>
        public ActionResult Pay(long orderid=81150718819501)
        {
            //TODO:将该页加入登录页,就可以启用下边的注释
            //var userid = UserInfo.UserId;
            //var openId = UserInfo.WxOpenId;
            var userid = 161;
            var openId = "oOGootzpwe38CkQSTj00wyHhKSMk";
            var order = OrderService.GetOrderViewModel(userid, orderid);
            if(string.IsNullOrEmpty(order.ProductName) || order.OrderId==0 || order.TotalMoney==0M)
            {
                return Content("ERROR");
            }
            var timeStamp = TenPayV3Util.GetTimestamp();
            var nonceStr = TenPayV3Util.GetNoncestr();

            var pre_id = WeixinPay.WeixinPayApi.Unifiedorder(order.ProductName, order.OrderId, order.TotalMoney, Request.UserHostAddress, openId);
            if (pre_id == "ERROR" || pre_id == "FAIL")
                return Content("ERROR");
            var package = "prepay_id=" + pre_id;

            var req = new RequestHandler(null);
            req.SetParameter("appId", AppId);
            req.SetParameter("timeStamp", timeStamp);
            req.SetParameter("nonceStr", nonceStr);
            req.SetParameter("package", package);
            req.SetParameter("signType", "MD5");
            var paySign = req.CreateMd5Sign("key", PayKey);

            //绑定页面数据
            ViewBag.TimeStamp = timeStamp;
            ViewBag.NonceStr = nonceStr;
            ViewBag.PaySign = paySign;
            ViewBag.Package = package;
            ViewBag.AppId = AppId;
            ViewBag.OrderId = order.OrderId;
            return View();
        }
示例#33
0
        /// <summary>
        /// 服务商
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="mchId"></param>
        /// <param name="subappid">子商户公众账号ID</param>
        /// <param name="submchid">子商户号</param>
        /// <param name="body"></param>
        /// <param name="outTradeNo"></param>
        /// <param name="totalFee">单位:分</param>
        /// <param name="spbillCreateIp"></param>
        /// <param name="notifyUrl"></param>
        /// <param name="tradeType"></param>
        /// <param name="openid">trade_type=NATIVE时,OpenId应该为null</param>
        /// <param name="subOpenid">用户子标识,不需要则填写null</param>
        /// <param name="key"></param>
        /// <param name="nonceStr"></param>
        /// <param name="deviceInfo">自定义参数,可以为终端设备号(门店号或收银设备ID),PC网页或公众号内支付可以传"WEB",String(32)如:013467007045764</param>
        /// <param name="timeStart">订单生成时间,如果为空,则默认为当前服务器时间</param>
        /// <param name="timeExpire">订单失效时间,留空则不设置失效时间</param>
        /// <param name="detail">商品详细列表</param>
        /// <param name="attach">附加数据</param>
        /// <param name="feeType">符合ISO 4217标准的三位字母代码,默认人民币:CNY</param>
        /// <param name="goodsTag">商品标记,使用代金券或立减优惠功能时需要的参数,说明详见代金券或立减优惠。String(32),如:WXG</param>
        /// <param name="productId">trade_type=NATIVE时(即扫码支付),此参数必传。此参数为二维码中包含的商品ID,商户自行定义。String(32),如:12235413214070356458058</param>
        /// <param name="limitPay">是否限制用户不能使用信用卡支付</param>
        public TenPayV3UnifiedorderRequestData(
            string appId, string mchId, string subappid, string submchid, string body, string outTradeNo, int totalFee, string spbillCreateIp,
            string notifyUrl, TenPayV3Type tradeType, string openid, string subOpenid, string key, string nonceStr,
            string deviceInfo = null, DateTime?timeStart = null, DateTime?timeExpire = null,
            string detail     = null, string attach      = null, string feeType = "CNY", string goodsTag = null,
            string productId  = null, bool limitPay      = false
            )
        {
            AppId          = appId;
            MchId          = mchId;
            DeviceInfo     = deviceInfo;
            NonceStr       = nonceStr;
            SignType       = "MD5";
            Body           = body ?? "Senparc TenpayV3";
            Detail         = detail;
            Attach         = attach;
            OutTradeNo     = outTradeNo;
            FeeType        = feeType;
            TotalFee       = totalFee;
            SpbillCreateIP = spbillCreateIp;
            TimeStart      = (timeStart ?? DateTime.Now).ToString("yyyyMMddHHmmss");
            TimeExpire     = timeExpire.HasValue ? timeExpire.Value.ToString("yyyyMMddHHmmss") : null;
            GoodsTag       = goodsTag;
            NotifyUrl      = notifyUrl;
            TradeType      = tradeType;
            ProductId      = productId;
            LimitPay       = limitPay ? "no_credit" : null;
            OpenId         = openid;
            Key            = key;
            SubAppId       = subappid;
            SubMchId       = submchid;
            SubOpenid      = subOpenid;


            #region 设置RequestHandler

            //创建支付应答对象
            PackageRequestHandler = new RequestHandler(null);
            //初始化
            PackageRequestHandler.Init();

            //设置package订单参数
            //以下设置顺序按照官方文档排序,方便维护:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
            PackageRequestHandler.SetParameter("appid", this.AppId);                       //公众账号ID
            PackageRequestHandler.SetParameter("mch_id", this.MchId);                      //商户号
            PackageRequestHandler.SetParameterWhenNotNull("sub_appid", this.SubAppId);     //子商户公众账号ID
            PackageRequestHandler.SetParameterWhenNotNull("sub_mch_id", this.SubMchId);    //子商户号
            PackageRequestHandler.SetParameterWhenNotNull("device_info", this.DeviceInfo); //自定义参数
            PackageRequestHandler.SetParameter("nonce_str", this.NonceStr);                //随机字符串
            PackageRequestHandler.SetParameterWhenNotNull("sign_type", this.SignType);     //签名类型,默认为MD5
            PackageRequestHandler.SetParameter("body", this.Body);                         //商品信息
            PackageRequestHandler.SetParameterWhenNotNull("detail", this.Detail);          //商品详细列表
            PackageRequestHandler.SetParameterWhenNotNull("attach", this.Attach);          //附加数据
            PackageRequestHandler.SetParameter("out_trade_no", this.OutTradeNo);           //商家订单号
            PackageRequestHandler.SetParameterWhenNotNull("fee_type", this.FeeType);       //符合ISO 4217标准的三位字母代码,默认人民币:CNY
            PackageRequestHandler.SetParameter("total_fee", this.TotalFee.ToString());     //商品金额,以分为单位(money * 100).ToString()
            PackageRequestHandler.SetParameter("spbill_create_ip", this.SpbillCreateIP);   //用户的公网ip,不是商户服务器IP
            PackageRequestHandler.SetParameterWhenNotNull("time_start", this.TimeStart);   //订单生成时间
            PackageRequestHandler.SetParameterWhenNotNull("time_expire", this.TimeExpire); //订单失效时间
            PackageRequestHandler.SetParameterWhenNotNull("goods_tag", this.GoodsTag);     //商品标记
            PackageRequestHandler.SetParameter("notify_url", this.NotifyUrl);              //接收财付通通知的URL
            PackageRequestHandler.SetParameter("trade_type", this.TradeType.ToString());   //交易类型
            PackageRequestHandler.SetParameterWhenNotNull("product_id", this.ProductId);   //trade_type=NATIVE时(即扫码支付),此参数必传。
            PackageRequestHandler.SetParameterWhenNotNull("limit_pay", this.LimitPay);     //上传此参数no_credit--可限制用户不能使用信用卡支付
            PackageRequestHandler.SetParameterWhenNotNull("openid", this.OpenId);          //用户的openId,trade_type=JSAPI时(即公众号支付),此参数必传
            PackageRequestHandler.SetParameterWhenNotNull("sub_openid", this.SubOpenid);   //用户子标识
            Sign = PackageRequestHandler.CreateMd5Sign("key", this.Key);
            PackageRequestHandler.SetParameter("sign", Sign);                              //签名
            #endregion
        }