Esempio n. 1
0
        public ActionResult JsApi(string code, string state)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

            if (!state.Contains("|"))
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return(Content("验证失败!请从正规途径进入!1001"));
            }
            try
            {
                //获取产品信息
                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 (string.IsNullOrEmpty(sp_billno))
                {
                    //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                    sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId, DateTime.Now.ToString("yyyyMMdd"),
                                              TenPayV3Util.BuildRandomStr(10));
                }
                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);

                if (res.Element("xml").Element("prepay_id") == null)
                {
                    throw new Exception(res.ToString().HtmlEncode());
                }

                //throw new Exception(res.ToString().HtmlEncode());
                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());
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                msg += "<br>" + ex.StackTrace;
                msg += "<br>==Source==<br>" + ex.Source;

                if (ex.InnerException != null)
                {
                    msg += "<br>===InnerException===<br>" + ex.InnerException.Message;
                }
                return(Content(msg));
            }
        }
Esempio n. 2
0
        public ActionResult ProductList()
        {
            var products = ProductModel.GetFakeProductList();

            return(View(products));
        }
        /// <summary>
        /// H5支付
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="hc"></param>
        /// <returns></returns>
        public ActionResult H5Pay(int productId, int hc)
        {
            {
                try
                {
                    //获取产品信息
                    var products = ProductModel.GetFakeProductList();
                    var product  = products.FirstOrDefault(z => z.Id == productId);
                    if (product == null || product.GetHashCode() != hc)
                    {
                        return(Content("商品信息不存在,或非法进入!1002"));
                    }

                    string openId = null;//此时在外部浏览器,无法或得到OpenId

                    string sp_billno = Request["order_no"];
                    if (string.IsNullOrEmpty(sp_billno))
                    {
                        //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                        sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"),
                                                  TenPayV3Util.BuildRandomStr(6));
                    }
                    else
                    {
                        sp_billno = Request["order_no"];
                    }

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

                    var body  = product == null ? "test" : product.Name;
                    var price = product == null ? 100 : (int)product.Price * 100;
                    //var ip = Request.Params["REMOTE_ADDR"];
                    var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPay.TenPayV3Type.MWEB /*此处无论传什么,方法内部都会强制变为MWEB*/, openId, TenPayV3Info.Key, nonceStr);

                    var result = TenPayV3.Html5Order(xmlDataInfo); //调用统一订单接口
                                                                   //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);

                    /*
                     * result:{"device_info":"","trade_type":"MWEB","prepay_id":"wx20170810143223420ae5b0dd0537136306","code_url":"","mweb_url":"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20170810143223420ae5b0dd0537136306\u0026package=1505175207","appid":"wx669ef95216eef885","mch_id":"1241385402","sub_appid":"","sub_mch_id":"","nonce_str":"juTchIZyhXvZ2Rfy","sign":"5A37D55A897C854F64CCCC4C94CDAFE3","result_code":"SUCCESS","err_code":"","err_code_des":"","return_code":"SUCCESS","return_msg":null}
                     */
                    //return Json(result, JsonRequestBehavior.AllowGet);

                    var package = string.Format("prepay_id={0}", result.prepay_id);

                    ViewData["product"] = product;

                    ViewData["appId"]     = TenPayV3Info.AppId;
                    ViewData["timeStamp"] = timeStamp;
                    ViewData["nonceStr"]  = nonceStr;
                    ViewData["package"]   = package;
                    ViewData["paySign"]   = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key);

                    //设置成功页面(也可以不设置,支付成功后默认返回来源地址)
                    var returnUrl =
                        string.Format("https://sdk.weixin.senparc.com/TenpayV3/H5PaySuccess?productId={0}&hc={1}",
                                      productId, hc);

                    var mwebUrl = result.mweb_url;
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        mwebUrl += string.Format("&redirect_url={0}", returnUrl.AsUrlData());
                    }

                    ViewData["MWebUrl"] = mwebUrl;

                    //临时记录订单信息,留给退款申请接口测试使用
                    Session["BillNo"]  = sp_billno;
                    Session["BillFee"] = price;

                    return(View());
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                    msg += "<br>" + ex.StackTrace;
                    msg += "<br>==Source==<br>" + ex.Source;

                    if (ex.InnerException != null)
                    {
                        msg += "<br>===InnerException===<br>" + ex.InnerException.Message;
                    }
                    return(Content(msg));
                }
            }
        }
        public ActionResult JsApi(int productId, int hc)
        {
            try
            {
                //获取产品信息
                var products = ProductModel.GetFakeProductList();
                var product  = products.FirstOrDefault(z => z.Id == productId);
                if (product == null || product.GetHashCode() != hc)
                {
                    return(Content("商品信息不存在,或非法进入!1002"));
                }

                //var openId = User.Identity.Name;
                var openId = (string)Session["OpenId"];

                string sp_billno = Request["order_no"];
                if (string.IsNullOrEmpty(sp_billno))
                {
                    //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                    sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"),
                                              TenPayV3Util.BuildRandomStr(6));
                }
                else
                {
                    sp_billno = Request["order_no"];
                }

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

                var body        = product == null ? "test" : product.Name;
                var price       = product == null ? 100 : (int)(product.Price * 100);//单位:分
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPay.TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr);

                var result = TenPayV3.Unifiedorder(xmlDataInfo); //调用统一订单接口
                                                                 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);
                var package = string.Format("prepay_id={0}", result.prepay_id);

                ViewData["product"] = product;

                ViewData["appId"]     = TenPayV3Info.AppId;
                ViewData["timeStamp"] = timeStamp;
                ViewData["nonceStr"]  = nonceStr;
                ViewData["package"]   = package;
                ViewData["paySign"]   = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key);

                //临时记录订单信息,留给退款申请接口测试使用
                Session["BillNo"]  = sp_billno;
                Session["BillFee"] = price;

                return(View());
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                msg += "<br>" + ex.StackTrace;
                msg += "<br>==Source==<br>" + ex.Source;

                if (ex.InnerException != null)
                {
                    msg += "<br>===InnerException===<br>" + ex.InnerException.Message;
                }
                return(Content(msg));
            }
        }
Esempio n. 5
0
        public ActionResult JsApi(string code, string state)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

            if (!state.Contains("|"))
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return(Content("验证失败!请从正规途径进入!1001"));
            }
            try
            {
                //获取产品信息
                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 sp_billno = Request["order_no"];
                if (string.IsNullOrEmpty(sp_billno))
                {
                    //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                    sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"),
                                              TenPayV3Util.BuildRandomStr(6));
                }
                //else
                //{
                //    sp_billno = Request["order_no"];
                //}

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

                var body        = product == null ? "test" : product.Name;
                var price       = product == null ? 100 : (int)product.Price * 100;
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openIdResult.openid, TenPayV3Info.Key, nonceStr);

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

                //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,);
                var package = string.Format("prepay_id={0}", result.prepay_id);

                ViewData["appId"]     = TenPayV3Info.AppId;
                ViewData["timeStamp"] = timeStamp;
                ViewData["nonceStr"]  = nonceStr;
                ViewData["package"]   = package;
                ViewData["paySign"]   = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key);

                return(View());
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                msg += "<br>" + ex.StackTrace;
                msg += "<br>==Source==<br>" + ex.Source;

                if (ex.InnerException != null)
                {
                    msg += "<br>===InnerException===<br>" + ex.InnerException.Message;
                }
                return(Content(msg));
            }
        }