Exemplo 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 sp_billno = Request["order_no"];
                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"];
                }

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

                var body        = product == null ? "test" : product.Name;
                var price       = product == null ? 100 : product.Price * 100;
                var xmlDataInfo = new TenPayV3RequestData(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));
            }
        }
Exemplo n.º 2
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());
        }
Exemplo n.º 3
0
        public ActionResult JsApi(string code, string state)
        {
            var sessionCount = GetSessionCount();

            sessionCount++;
            SetSessionCount(sessionCount);
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

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



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

            //return Content(string.Format("已經到這裡 {0}:{1}", stateData[0], stateData[1]));
            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;
                }
            }
            var identityNo = state[2];  //身份证号码

            string openId;
            OAuthAccessTokenResult openIdResult = null;

            #region 解決 Auth 出現 40028(Invalid code)錯誤
            try
            {
                //通过,用code换取access_token

                var isSecondRequest = false;
                lock (OAuthCodeCollectionLock)
                {
                    isSecondRequest = OAuthCodeCollection.ContainsKey(code);
                }

                if (!isSecondRequest)
                {
                    //第一次请求
                    //LogUtility.Weixin.DebugFormat("第一次微信OAuth到达,code:{0}", code);
                    lock (OAuthCodeCollectionLock)
                    {
                        OAuthCodeCollection[code] = null;
                    }
                }
                else
                {
                    //第二次请求
                    //LogUtility.Weixin.DebugFormat("第二次微信OAuth到达,code:{0}", code);

                    lock (OAuthCodeCollectionLock)
                    {
                        openIdResult = OAuthCodeCollection[code];
                    }
                }

                try
                {
                    try
                    {
                        openIdResult = openIdResult ?? OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code);
                    }
                    catch (Exception ex)
                    {
                        return(Content("OAuth AccessToken错误:" + ex.Message));
                    }

                    if (openIdResult != null)
                    {
                        lock (OAuthCodeCollectionLock)
                        {
                            OAuthCodeCollection[code] = openIdResult;
                        }
                    }
                }
                catch (ErrorJsonResultException ex)
                {
                    if (ex.JsonResult.errcode == ReturnCode.合法的oauth_code)
                    {
                        //code已经被使用过
                        lock (OAuthCodeCollectionLock)
                        {
                            openIdResult = OAuthCodeCollection[code];
                        }
                    }
                }

                openId = openIdResult != null ? openIdResult.openid : null;
            }
            catch (Exception ex)
            {
                return(Content("授权过程发生错误:" + ex.Message));
            }
            #endregion


            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());
        }