public static wxPayReturnValue OAuth2_Access_Token(string Code)
        {
            StringBuilder sbCode = new StringBuilder(OAUTH2_ACCESS_TOKEN);

            sbCode.Append("?appid=" + APPID);
            sbCode.Append("&secret=" + APPSECRET);
            sbCode.Append("&code=" + Code);
            sbCode.Append("&grant_type=authorization_code");

            wxPayReturnValue retValue = StreamReaderUtils.StreamReader(sbCode.ToString(), Encoding.UTF8);

            if (retValue.HasError)
            {
                return(retValue);
            }

            try
            {
                UserAccessToken uat = JSONHelper.JSONToObject <UserAccessToken>(retValue.Message);
                retValue.PutValue("Weixin_OpenID", uat.openid);
                retValue.PutValue("Weixin_Token", uat.access_token);
                //retValue.PutValue("Weixin_ExpiresIn", intWeixin_ExpiresIn);
                //retValue.PutValue("Weixin_ExpiresDate", DateTime.Now.AddSeconds(intWeixin_ExpiresIn));
                //retValue.PutValue("refresh_token", StringUtils.GetJsonValue(retValue.Message, "refresh_token").ToString());
                //retValue.PutValue("scope", StringUtils.GetJsonValue(retValue.Message, "scope").ToString());
            }
            catch
            {
                retValue.HasError = true;
                //  retValue.Message = retValue.Message;
                retValue.ErrorCode = "";
            }

            return(retValue);
        }
示例#2
0
        // GET: area12/jsapiPay
        public ActionResult Index()
        {
            string strBillNo        = wxPayService.getTimestamp();                                            // 订单号
            string strWeixin_OpenID = "";                                                                     // 当前用户的openid
            string strCode          = Request.QueryString["code"] == null ? "" : Request.QueryString["code"]; // 接收微信认证服务器发送来的code

            LogService.Write("code:" + strCode);

            if (string.IsNullOrEmpty(strCode)) //如果接收到code,则说明是OAuth2服务器回调
            {
                //进行OAuth2认证,获取code
                string _OAuth_Url = wxPayService.OAuth2_GetUrl_Pay(Request.Url.ToString());

                LogService.Write("_OAuth_Url:" + _OAuth_Url);
                Response.Redirect(_OAuth_Url);
                return(Content(""));
            }
            else
            {
                //根据返回的code,获得
                wxPayReturnValue retValue = wxPayService.OAuth2_Access_Token(strCode);

                if (retValue.HasError)
                {
                    Response.Write("获取code失败:" + retValue.Message);
                    return(Content(""));
                }
                LogService.Write("retValue.Message:" + retValue.Message);

                strWeixin_OpenID = retValue.GetStringValue("Weixin_OpenID");
                string strWeixin_Token = retValue.GetStringValue("Weixin_Token");
                LogService.Write("strWeixin_OpenID:" + strWeixin_OpenID);

                if (string.IsNullOrEmpty(strWeixin_OpenID))
                {
                    Response.Write("openid出错");
                    return(Content(""));
                }
            }
            if (string.IsNullOrEmpty(strWeixin_OpenID))
            {
                return(Content(""));
            }

            wxpayPackage pp = wxPayService.MakePayPackage(strWeixin_OpenID, strBillNo, 0.01M, "测试");

            //  LogService.Write("_Pay_json1:" + _Pay_json);
            ViewBag.appid     = pp.appId;
            ViewBag.nonceStr  = pp.nonceStr;
            ViewBag.package   = pp.package;
            ViewBag.paySign   = pp.paySign;
            ViewBag.signType  = pp.signType;
            ViewBag.timeStamp = pp.timeStamp;

            return(View());
        }
示例#3
0
        public static wxPayReturnValue StreamReaderLoop(string RequestURI, Encoding Encode)
        {
            HttpWebRequest  req    = WebRequest.Create(RequestURI) as HttpWebRequest;
            HttpWebResponse resp   = (HttpWebResponse)req.GetResponse();
            Stream          stream = resp.GetResponseStream();
            StreamReader    reader = new StreamReader(stream, Encode);

            wxPayReturnValue retValue = new wxPayReturnValue();

            string strReturn = "";
            int    length    = 0x400;

            char[] buf = new char[length];
            try
            {
                int i = 0;
                do
                {
                    i          = reader.Read(buf, 0, length);
                    strReturn += new string(buf, 0, i);
                    Array.Clear(buf, 0, length);
                } while (i > 0);
            }
            catch
            {
                int index = Array.IndexOf <char>(buf, '\0');
                if (index >= 0)
                {
                    strReturn += new string(buf, 0, index);
                }
            }
            finally
            {
                reader.Close();
                stream.Close();
                resp.Close();
            }

            retValue.Message = strReturn;

            return(retValue);
        }
示例#4
0
        public ActionResult redpack()
        {
            string strBillNo = wxPayService.getTimestamp(); // 订单号
            // 接收微信认证服务器发送来的code
            string strCode = Request.QueryString["code"] == null ? "" : Request.QueryString["code"];

            LogService.Write("code:" + strCode);
            ViewBag.OpenId = "";
            if (string.IsNullOrEmpty(strCode)) //如果接收到code,则说明是OAuth2服务器回调
            {
                //进行OAuth2认证,获取code
                string _OAuth_Url = wxPayService.OAuth2_GetUrl_Pay(Request.Url.ToString());

                LogService.Write("_OAuth_Url:" + _OAuth_Url);
                Response.Redirect(_OAuth_Url);
                return(View());
            }
            else
            {
                //根据返回的code,获得Access_Token
                wxPayReturnValue retValue = wxPayService.OAuth2_Access_Token(strCode);

                if (retValue.HasError)
                {
                    Response.Write("获取code失败:" + retValue.Message);
                    return(Content(""));
                }
                LogService.Write("retValue.Message:" + retValue.Message);

                string strWeixin_OpenID = retValue.GetStringValue("Weixin_OpenID");
                string strWeixin_Token  = retValue.GetStringValue("Weixin_Token");
                LogService.Write("strWeixin_OpenID:" + strWeixin_OpenID);

                ViewBag.OpenId = strWeixin_OpenID;
            }

            return(View());
        }
        //public static readonly string NOTIFY_URL_Card_Store = "/wx/WXPayNotify_URL.aspx";// ConfigurationManager.AppSettings["WXPayNotify_URL_CardStore"].ToString();
        //public static readonly string NOTIFY_URL_Card_User = "******"; //ConfigurationManager.AppSettings["WXPayNotify_URL_CardUser"].ToString();
        //public static readonly string NOTIFY_URL_HB_Store = "/wx/WXPayNotify_URL.aspx";// ConfigurationManager.AppSettings["WXPayNotify_URL_CardStore"].ToString();

        /// <summary>
        /// 生成支付Json字符串(发送给财付通的报文)
        /// </summary>
        /// <param name="openid">支付用户的openid</param>
        /// <param name="Bill_No">订单号</param>
        /// <param name="Charge_Amt">支付金额</param>
        /// <param name="Body">支付描述</param>
        /// <returns>支付Json字符串</returns>
        public static wxpayPackage MakePayPackage(string openid, string Bill_No, decimal Charge_Amt, string Body)
        {
            HttpContext Context = System.Web.HttpContext.Current;

            if (openid.Length == 0)
            {
                return(null);
            }
            // *********** here ************
            //设置package订单参数
            SortedDictionary <string, string> dic = new SortedDictionary <string, string>();

            string total_fee    = (Charge_Amt * 100).ToString("f0");      // 支付金额单位为分
            string wx_timeStamp = "";                                     //时间戳
            string wx_nonceStr  = getNoncestr();                          //随机字符串

            dic.Add("appid", APPID);                                      //微信APPID

            dic.Add("mch_id", PARTNER);                                   //商家的财付通帐号
            dic.Add("device_info", "1000");                               //设备号,可为空
            dic.Add("nonce_str", wx_nonceStr);                            // 随机字符串
            dic.Add("trade_type", "JSAPI");                               //交易类型
            dic.Add("attach", "att1");                                    // 附加数据
            dic.Add("openid", openid);                                    // 支付用户的openid
            dic.Add("out_trade_no", Bill_No);                             //商家订单号
            dic.Add("total_fee", total_fee);                              //商品金额,以分为单位(money * 100).ToString()
            dic.Add("notify_url", TENPAY_NOTIFY.ToLower());               //接收财付通通知的URL
            dic.Add("body", Body);                                        //商品描述
            dic.Add("spbill_create_ip", Context.Request.UserHostAddress); //用户的公网ip,不是商户服务器IP

            string get_sign = MakeSignstr(dic, PARTNER_KEY);

            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";  // 统一支付接口
            // 支付接口
            string _req_data = "<xml>";

            _req_data += "<appid>" + APPID + "</appid>";
            _req_data += "<attach><![CDATA[att1]]></attach>";
            _req_data += "<body><![CDATA[" + Body + "]]></body> ";
            _req_data += "<device_info><![CDATA[1000]]></device_info> ";
            _req_data += "<mch_id><![CDATA[" + PARTNER + "]]></mch_id> ";
            _req_data += "<openid><![CDATA[" + openid + "]]></openid> ";
            _req_data += "<nonce_str><![CDATA[" + wx_nonceStr + "]]></nonce_str> ";
            _req_data += "<notify_url><![CDATA[" + TENPAY_NOTIFY.ToLower() + "]]></notify_url> ";
            _req_data += "<out_trade_no><![CDATA[" + Bill_No + "]]></out_trade_no> ";
            _req_data += "<spbill_create_ip><![CDATA[" + Context.Request.UserHostAddress + "]]></spbill_create_ip> ";
            _req_data += "<total_fee><![CDATA[" + total_fee + "]]></total_fee> ";
            _req_data += "<trade_type><![CDATA[JSAPI]]></trade_type> ";
            _req_data += "<sign><![CDATA[" + get_sign + "]]></sign> ";
            _req_data += "</xml>";

            //通知支付接口,拿到prepay_id
            wxPayReturnValue retValue = StreamReaderUtils.StreamReader(url, Encoding.UTF8.GetBytes(_req_data), System.Text.Encoding.UTF8, true);

            #region 获取prepay_id, 设置支付参数
            XmlDocument xmldoc = new XmlDocument();


            xmldoc.LoadXml(retValue.Message);

            XmlNode Event = xmldoc.SelectSingleNode("/xml/prepay_id");

            wxpayPackage pp = new wxpayPackage();

            if (Event != null)
            {
                string _prepay_id = Event.InnerText;

                SortedDictionary <string, string> pay_dic = new SortedDictionary <string, string>();

                wx_timeStamp = getTimestamp();
                wx_nonceStr  = getNoncestr();

                string _package = "prepay_id=" + _prepay_id;

                pay_dic.Add("appId", APPID);
                pay_dic.Add("timeStamp", wx_timeStamp);
                pay_dic.Add("nonceStr", wx_nonceStr);
                pay_dic.Add("package", _package);
                pay_dic.Add("signType", "MD5");

                string get_PaySign = MakeSignstr(pay_dic, PARTNER_KEY);



                pp.appId     = APPID;
                pp.timeStamp = wx_timeStamp;
                pp.nonceStr  = wx_nonceStr;
                pp.package   = _package;
                pp.paySign   = get_PaySign;
                pp.signType  = "MD5";
            }
            #endregion
            return(pp);
        }
示例#6
0
        public ActionResult JSPay(decimal money)
        {
            if (Session["OpenID"] != null)
            {
                string q    = Session["OpenID"].ToString();
                var    user = (from x in db.User where x.OpenID == q select x).FirstOrDefault();
                if (user != null)
                {
                    Session["ID"] = user.ID.ToString();
                    ////ID = user.ID.ToString();
                }
                else
                {
                    return(RedirectToAction("Login", "Home"));
                }
            }

            string strBillNo = wxPayService.getTimestamp();                                                   // 订单号

            string strWeixin_OpenID = "";                                                                     // 当前用户的openid
            string strCode          = Request.QueryString["code"] == null ? "" : Request.QueryString["code"]; // 接收微信认证服务器发送来的code



            if (string.IsNullOrEmpty(strCode)) //如果接收到code,则说明是OAuth2服务器回调
            {
                //进行OAuth2认证,获取code
                string _OAuth_Url = wxPayService.OAuth2_GetUrl_Pay(Request.Url.ToString());


                Response.Redirect(_OAuth_Url);

                return(Content(""));
            }
            else
            {
                //根据返回的code,获得
                wxPayReturnValue retValue = wxPayService.OAuth2_Access_Token(strCode);


                if (retValue.HasError)
                {
                    Response.Write("获取code失败:" + retValue.Message);
                    return(Content(""));
                }


                strWeixin_OpenID = retValue.GetStringValue("Weixin_OpenID");
                string strWeixin_Token = retValue.GetStringValue("Weixin_Token");

                if (string.IsNullOrEmpty(strWeixin_OpenID))
                {
                    Response.Write("openid出错");
                    return(Content(""));
                }
            }
            if (string.IsNullOrEmpty(strWeixin_OpenID))
            {
                return(Content(""));
            }

            wxpayPackage pp = wxPayService.MakePayPackage(strWeixin_OpenID, strBillNo, money, "微来时空");

            //  LogService.Write("_Pay_json1:" + _Pay_json);
            ViewBag.appid     = pp.appId;
            ViewBag.nonceStr  = pp.nonceStr;
            ViewBag.package   = pp.package;
            ViewBag.paySign   = pp.paySign;
            ViewBag.signType  = pp.signType;
            ViewBag.timeStamp = pp.timeStamp;
            ViewBag.money     = money;


            return(View());
        }
示例#7
0
        public static wxPayReturnValue StreamReader(string RequestURI, byte[] RequestData, Encoding Encode, bool Post)
        {
            System.Net.ServicePointManager.Expect100Continue = true;

            wxPayReturnValue retValue = new wxPayReturnValue();

            if (Encode == null)
            {
                Encode = System.Text.Encoding.GetEncoding("utf-8");
            }
            string         strReturnCode;
            HttpWebRequest myHttpWebRequest = null;

            //如果是发送HTTPS请求
            if (RequestURI.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(RequestURI);
                myHttpWebRequest.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(RequestURI);
            }

            try
            {
                byte[] bs;
                if (Post)
                {
                    myHttpWebRequest.Method      = "POST";
                    myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    bs = RequestData;

                    myHttpWebRequest.ContentLength = bs.Length;

                    using (Stream reqStream = myHttpWebRequest.GetRequestStream())
                    {
                        reqStream.Write(bs, 0, bs.Length);
                    }
                }
                else
                {
                    myHttpWebRequest.Method = "GET";
                }
                using (WebResponse myWebResponse = myHttpWebRequest.GetResponse())
                {
                    StreamReader readStream = new StreamReader(myWebResponse.GetResponseStream(), Encode);
                    strReturnCode = readStream.ReadToEnd();
                }

                retValue.HasError     = false;
                retValue.Message      = strReturnCode;
                retValue.ReturnObject = null;
            }
            catch (Exception ex)
            {
                retValue.HasError     = true;
                retValue.Message      = "请求接口信息出错";
                retValue.ReturnObject = ex;
            }
            return(retValue);
        }