Пример #1
0
 /**
  *
  * 网页授权获取用户基本信息的全部过程
  * 详情请参看网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
  * 第一步:利用url跳转获取code
  * 第二步:利用code去获取openid和access_token
  *
  */
 public void GetOpenidAndAccessToken()
 {
     if (Session["code"] != null)
     {
         //获取code码,以获取openid和access_token
         string code = Session["code"].ToString();
         Log.Debug(this.GetType().ToString(), "Get code : " + code);
         jsApiPay.GetOpenidAndAccessTokenFromCode(code);
     }
     else
     {
         //构造网页授权获取code的URL
         string host         = Request.Url.Host;
         string path         = Request.Path;
         string redirect_uri = HttpUtility.UrlEncode("http://" + host + path);
         //string redirect_uri = HttpUtility.UrlEncode("http://gzh.lmx.ren");
         WxPayData data = new WxPayData();
         data.SetValue("appid", WxPayConfig.APPID);
         data.SetValue("redirect_uri", redirect_uri);
         data.SetValue("response_type", "code");
         data.SetValue("scope", "snsapi_base");
         data.SetValue("state", "STATE" + "#wechat_redirect");
         string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
         Log.Debug(this.GetType().ToString(), "Will Redirect to URL : " + url);
         Session["url"] = url;
     }
 }
Пример #2
0
        public ActionResult GetLogin(string code)
        {
            JsApiPay jsapi = new JsApiPay();

            jsapi.GetOpenidAndAccessTokenFromCode(code);

            string sessionid = Guid.NewGuid().ToString("N");

            Session[sessionid] = jsapi.openid + "|" + jsapi.access_token;

            var user = UserBLL.Read(jsapi.openid);

            if (user.Id > 0)
            {
                UserBLL.UserLoginInit(user);
                //VirtualUser vuser = new VirtualUser()
                //{
                //    id = user.Id,
                //    name = HttpUtility.UrlDecode(user.UserName, System.Text.Encoding.UTF8),
                //};
                var vuser = new
                {
                    id     = user.Id,
                    name   = HttpUtility.UrlDecode(user.UserName, System.Text.Encoding.UTF8),
                    status = user.Status,
                    avatar = user.Photo
                };
                return(Json(new { flag = true, sessionid = sessionid, userinfo = vuser, thesessionid = Session.SessionID }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new { flag = false, msg = "no user", openid = jsapi.openid, sessionid = sessionid, thesessionid = Session.SessionID }, JsonRequestBehavior.AllowGet));
            }
        }
Пример #3
0
        public BaseApiResponse GetOpenIdAndAccessToken(string code)
        {
            code.CheckNotNullOrEmpty(nameof(code));
            JsApiPay jsApiPay = new JsApiPay();

            jsApiPay.GetOpenidAndAccessTokenFromCode(code);
            return(new GetOpenIdAndAccessTokenResponse {
                Message = "", openid = jsApiPay.openid, access_token = jsApiPay.access_token
            });
        }
Пример #4
0
        public ActionResult getWxInfo(string code)
        {
            object objResult = "";
            string strCode   = code;

            if (Session["access_token"] == null || Session["openid"] == null)
            {
                jsApiPay.GetOpenidAndAccessTokenFromCode(strCode);
            }
            string strAccess_Token = Session["access_token"].ToString();
            string strOpenid       = Session["openid"].ToString();

            objResult = new { openid = strOpenid, access_token = strAccess_Token };
            return(Json(objResult));
        }
Пример #5
0
        public ActionResult getWxInfo()
        {
            object objResult = "";
            string strCode   = Request.Form["code"];

            log.Error($"code:{strCode}");
            if (Session["access_token"] == null || Session["openid"] == null)
            {
                jsApiPay.GetOpenidAndAccessTokenFromCode(strCode);
            }
            string strAccess_Token = Session["access_token"].ToString();
            string strOpenid       = Session["openid"].ToString();

            objResult = new { openid = strOpenid, access_token = strAccess_Token };
            return(Json(objResult));
        }
Пример #6
0
        //weixin  getphonenumber 解密
        public ActionResult DecryptAES(string encryptedDataStr, string iv, string code)
        {
            //iv = iv.Replace(" ", "+");
            //sessionKey = sessionKey.Replace(" ", "+");
            //encryptedDataStr = encryptedDataStr.Replace(" ", "+");
            JsApiPay jsapi = new JsApiPay();

            jsapi.GetOpenidAndAccessTokenFromCode(code);
            if (jsapi.access_token != string.Empty)
            {
                RijndaelManaged rijalg = new RijndaelManaged();
                //设置 cipher 格式 AES-128-CBC

                rijalg.KeySize = 128;
                rijalg.Padding = PaddingMode.PKCS7;
                rijalg.Mode    = CipherMode.CBC;

                rijalg.Key = Convert.FromBase64String(jsapi.access_token);
                rijalg.IV  = Convert.FromBase64String(iv);


                byte[] encryptedData = Convert.FromBase64String(encryptedDataStr);
                //解密
                ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);

                string result;

                using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            result = srDecrypt.ReadToEnd();
                        }
                    }
                }
                var phoneInfo = JsonConvert.DeserializeObject <WxPhone>(result);
                return(Json(new { ok = true, data = phoneInfo }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new { ok = false, errmsg = "无效Code" }, JsonRequestBehavior.AllowGet));
            }
        }
Пример #7
0
        /// <summary>
        /// 充值回调
        /// </summary>
        /// <param name="code">回调code</param>
        /// <param name="state">回调携带的参数:IdAmount 订单ID 或者 充值金额+"|" </param>
        /// <returns></returns>
        public ActionResult Default(string code, string state)
        {
            RecordService RecSVC       = new RecordService();
            Bis_Record    recordEntity = new Bis_Record();

            ViewBag.tipStr = "微信支付正在处理...";

            if (!state.Contains("|"))
            {
                // 订单消费
                ViewBag.Flag = "";
                var OrderID = Convert.ToString(state);

                // 根据订单ID查询订单信息
                recordEntity = RecSVC.SelectByID(OrderID);
                if (recordEntity == null)
                {
                    ViewBag.tipStr = "订单信息存在问题,请返回重试";
                    return(View(recordEntity));
                }
                //// 测试订单金额 0.02
                //recordEntity.Amount = Convert.ToDecimal(0.02);
                if (recordEntity.Amount <= 0)
                {
                    ViewBag.tipStr = "支付金额必须大于0,请返回重试";
                    return(View(recordEntity));
                }

                // 创建微信支付参数
                JsApiPay jsApiPay = new JsApiPay(this);
                jsApiPay.GetOpenidAndAccessTokenFromCode(code);
                jsApiPay.total_fee = Convert.ToInt32(recordEntity.Amount * 100);
                jsApiPay.order_no  = recordEntity.OrderNo;
                jsApiPay.attach    = recordEntity.UserID;

                if (string.IsNullOrEmpty(jsApiPay.openid) || jsApiPay.total_fee <= 0)
                {
                    ViewBag.tipStr = "页面参数出错,请返回重试";
                    return(View(recordEntity));
                }

                // JSAPI支付预处理
                try
                {
                    WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult();
                    string    wxJsApiParam       = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数
                    ViewBag.wxJsApiParam = wxJsApiParam;
                }
                catch (Exception ex)
                {
                    ViewBag.tipStr = "下单失败,请返回重试";
                    MYLog.Error("下单失败,请返回重试:" + SessionTools.UserName, ex.ToString());
                }
            }
            else
            {
                // 订单充值
                ViewBag.Flag = "1";

                // 判断充值金额
                var money = Convert.ToDecimal(state.Substring(0, state.Length - 1));
                if (money < Convert.ToDecimal(0.01))
                {
                    ViewBag.tipStr = "充值金额不能低于0.01";
                    return(View(recordEntity));
                }

                // 创建充值订单
                var resultData = RecSVC.SubmitRecharge(money, SessionTools.UserID);
                if (!(resultData != null && resultData.status > 0))
                {
                    ViewBag.tipStr = "创建充值订单失败";
                    return(View(recordEntity));
                }

                // 取得订单信息
                recordEntity = resultData.data;
                if (recordEntity.Amount <= 0)
                {
                    ViewBag.tipStr = "支付金额必须大于0,请返回重试";
                    return(View(recordEntity));
                }

                // 创建微信支付参数
                JsApiPay jsApiPay = new JsApiPay(this);
                jsApiPay.GetOpenidAndAccessTokenFromCode(code);//openid
                jsApiPay.total_fee = Convert.ToInt32(recordEntity.Amount * 100);
                jsApiPay.order_no  = recordEntity.OrderNo;
                jsApiPay.attach    = recordEntity.UserID.ToString() + "|";

                if (string.IsNullOrEmpty(jsApiPay.openid) || jsApiPay.total_fee <= 0)
                {
                    ViewBag.tipStr = "页面参数出错,请返回重试";
                    return(View(recordEntity));
                }

                //JSAPI支付预处理
                try
                {
                    WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult();
                    string    wxJsApiParam       = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数
                    ViewBag.wxJsApiParam = wxJsApiParam;
                }
                catch (Exception ex)
                {
                    ViewBag.tipStr = "充值失败,请返回重试";
                    MYLog.Error("充值失败,请返回重试:" + SessionTools.UserName, ex.ToString());
                }
            }
            return(View(recordEntity));
        }
Пример #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request.QueryString["code"]))
            {
                imei = Request.QueryString["imei"];
                string vc = Request.QueryString["vc"];
                total_fee = Convert.ToInt32(Request.QueryString["p"]);
                userid    = Convert.ToInt32(Request.QueryString["userid"]);
                status    = Convert.ToInt32(Request.QueryString["s"]);
                var ru = HttpUtility.UrlEncode($"http://m.mgoogps.com/Pay/PayConfirm.aspx?imei={imei}&vc={vc}&p={total_fee}&userid={userid}&s={status}");

                var url = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={WxPayConfig.APPID}&redirect_uri={ru}&response_type=code&scope=snsapi_base&state=snsapi_base#wechat_redirect";
                //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxda27104d229a3608&redirect_uri=http://m.mgoogps.com/Pay/PayConfirm.aspx?imei=1&vc=12&p=1223&response_type=code&scope=snsapi_base&state=snsapi_base#wechat_redirect
                Response.Redirect(url);
                Response.End();
            }
            if (!IsPostBack)
            {
                imei = Request.QueryString["imei"];
                string vc = Request.QueryString["vc"];
                total_fee = Convert.ToInt32(Request.QueryString["p"]);
                var code = Request.QueryString["code"];
                userid = Convert.ToInt32(Request.QueryString["userid"]);
                status = Convert.ToInt32(Request.QueryString["s"]);
                if (userid == 0)
                {
                    state = "参数错误!";
                    return;
                }
                MG_DAL.YiwenGPSEntities db = new MG_DAL.YiwenGPSEntities();
                var device = db.Devices.Where(d => d.Deleted == false && d.SerialNumber == imei && d.DevicePassword == vc).SingleOrDefault();
                prductName = "北斗GPS流量费(2年)-" + (string.IsNullOrEmpty(device.DeviceName) ? device.SerialNumber : device.DeviceName);
                JsApiPay jsApiPay = new JsApiPay(this);
                if (device.Model.Equals("80")) //MG-X21BZ
                {
                    jsApiPay.tariff_id = 8;
                    total_fee          = 240;
                }
                else
                {
                    jsApiPay.tariff_id = 9;
                    total_fee          = 195;
                }

                //JSAPI支付预处理
                try
                {
                    var userList = new List <int>()
                    {
                        6, 7, 5959, 1296, 1389, 1331, 6093
                    };
                    // total_fee = ( type == "1" ? int.Parse(total_fee) :int.Parse( total_fee) )+"";
                    jsApiPay.user_id = userid;// (int)device.UserID;
                    //jsApiPay.openid = openid;
                    jsApiPay.total_fee = userList.Contains(jsApiPay.user_id)? new Random().Next(1, 10) : Convert.ToInt32(total_fee) * 100;
                    jsApiPay.device_id = device.DeviceID;

                    jsApiPay.product_body = prductName;
                    jsApiPay.device_name  = "success_notify," + device.DeviceID + "," + userid + "," + status;//attach 商家数据包,原样返回, status :1 账号已存在,2是新注册的账号
                    if (total_fee < 195 && !userList.Contains(jsApiPay.user_id))
                    {
                        state = "下单失败,金额错误!";
                        return;
                    }
                    jsApiPay.GetOpenidAndAccessTokenFromCode(code);

                    WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult();
                    wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数

                    jsApiPay.InsertMgooOrder();

                    //下单成功后的内部订单号
                    order_no     = jsApiPay.order_no;
                    callback_url = "../PayActivation/payResult.html?no=" + order_no.ToString() + "&deviceid=" + device.DeviceID + "&t=" + DateTime.Now.Ticks;
                    Log.Debug(this.GetType().ToString(), "wxJsApiParam : " + wxJsApiParam);

                    //在页面上显示订单信息
                    // Response.Write("<span style='color:#00CD00;font-size:20px' id='payRes'>订单详情:</span><br/>");
                    // Response.Write("<span style='color:#00CD00;font-size:20px'>" + unifiedOrderResult.ToPrintStr() + "</span>");
                }
                catch (System.Net.WebException ex)
                {
                    MG_BLL.Common.Log.Error(this, ex);
                    //state = ex.Message;
                    state = "网络繁忙,请稍后再试!";
                }
                catch (Exception ex)
                {
                    state = "下单失败,请稍后再试!";
                    MG_BLL.Common.Log.Error(this, ex);
                    //state = ex.Message;
                    // Utils.log("下单失败:userid:" + userid + ",deviceid:" + deviceid + ",total_fee:" + Convert.ToInt32(total_fee) + ",openid:" + openid + ",tariff_id:" + tariff_id + ",tariff_name:" + tariff_name + ",device_name:" + device_name + ",type:" + type);
                    //Response.Write("<span style='color:#FF0000;font-size:20px'>" + "下单失败,请返回重试" + "</span>");
                    // submit.Visible = false;
                }
            }
        }
Пример #9
0
        public ActionResult OrderConfirm()
        {
            string paycode = QueryString.SafeQ("code");

            int success  = QueryString.IntSafeQ("s");  //是否需要订单成功提醒
            int freshnum = QueryString.IntSafeQ("fn"); //循环次数,超过10次自动关闭

            if (freshnum > 10)
            {
                return(null);
            }
            VWPayOrderEntity _payen = PayOrderBLL.Instance.GetVWPayOrderByPayCode(paycode);

            if (_payen.PayMethod == (int)PayType.WeChat)//微信支付
            {
                if (Globals.IsWeiXinDevice())
                {
                    string wechatcode = "";
                    wechatcode = QueryString.SafeQ("wechatcode");

                    //是微信客户端走这边
                    if (string.IsNullOrEmpty(wechatcode))
                    {
                        //没有获取微信授权码
                        string url         = Request.Url.ToString();
                        string redirecturl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(url), "0");
                        return(Redirect(redirecturl));
                    }
                    else
                    {
                        //有微信授权码
                        JsApiPay jsApiPay = new JsApiPay();
                        try
                        {
                            jsApiPay.GetOpenidAndAccessTokenFromCode(wechatcode);
                        }
                        catch (Exception ex)
                        {
                            //授权码过期
                            string baseurl;
                            Dictionary <string, string> nvc = new Dictionary <string, string>();
                            string oldurl = Request.Url.ToString();
                            StringUtils.ParseUrl(oldurl, out baseurl, out nvc);
                            nvc.Remove("wechatcode");
                            if (nvc.ContainsKey("fn"))
                            {
                                nvc["fn"] = (StringUtils.GetDbInt(nvc["fn"]) + 1).ToString();
                            }
                            else
                            {
                                nvc.Add("fn", "1");
                            }
                            string url = baseurl + "?";
                            foreach (string key in nvc.Keys)
                            {
                                url += "&" + key + "=" + nvc[key];
                            }

                            string redirecturl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(url), "0");
                            return(Redirect(redirecturl));
                        }
                        WxPayData paydata      = jsApiPay.GetUnifiedOrderResult(_payen);
                        string    wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数
                        ViewBag.WeiXinJsApiParam = wxJsApiParam;
                    }
                }
                else
                {
                    //网站类调出微信端支付通道
                    DateTime  dtnow     = DateTime.Now;
                    NativePay nativePay = new NativePay();
                    WxPayData data      = nativePay.GetPayUrl(_payen, "MWEB");//得到调用微信接口的路径
                    string    url       = data.GetValue("mweb_url").ToString();
                    return(Redirect(url));
                }
            }
            ViewBag.PayOrderEntity = _payen;
            ViewBag.Success        = success;
            return(View());
        }
Пример #10
0
        /// <summary>
        /// WAP在线支付JSPAI页面
        /// </summary>
        /// <param name="requestSysNo"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult OnlineWapPayJSAPI(int requestSysNo, string code)
        {
            try
            {
                var onlinePay = Builder.BuildOnlinePay();

                //获取支付请求记录
                var requestInfo = PayRequestDAL.GetPayRequest(requestSysNo);
                if (requestInfo == null || requestInfo.SysNo <= 0)
                {
                    ViewBag.ErrorMsg = "您尚未发起支付请求,请返回后重新提交";
                    return(View());
                }

                //校验支付环境
                var checkResult = onlinePay.CheckBrowserType(AppEnum.BrowserType.WeChat, requestInfo);
                if (checkResult.Status != ResultStatus.Success)
                {
                    ViewBag.ErrorMsg = checkResult.Message;
                    return(View());
                }

                #region 组装浏览器调起JS API支付所需的参数
                try
                {
                    var jsApiPay = new JsApiPay(System.Web.HttpContext.Current);
                    //获取授权用户信息
                    jsApiPay.GetOpenidAndAccessTokenFromCode(code);
                    //获取订单支付金额
                    int paymentAmt = (int)(requestInfo.PaymentAmt * 100);//微信支付金额的单位为“分”,所以要乘以100
                    //异步通知url
                    string notifyUrl = string.Format("http://{0}/SwiftPassWeChatPay/OnlinePayNotify", AppConfig.Global.Domain);

                    var      orderInfo     = JsonHelper.Deserialize <PayOrderInfo>(requestInfo.RequestData);
                    DateTime orderEndTime  = DateTime.ParseExact(orderInfo.OrderTime, "yyyyMMddHHmmss", new CultureInfo("zh-CN", true)).AddHours(24);
                    DateTime minExpireTime = DateTime.Now.AddMinutes(6);//为保险,多加1分钟
                    //交易过期时间(最短过期时间间隔必须大于5分钟)
                    string expireTime = (orderEndTime > minExpireTime ? orderEndTime : minExpireTime).ToString("yyyyMMddHHmmss");
                    //获取调起JS API的参数
                    ViewBag.JsApiParams = SwiftPassPayApi.WeChatJsApiPay(requestInfo.OrderId, paymentAmt, notifyUrl, expireTime, jsApiPay.openid);
                    //订单编号
                    ViewBag.OrderId = requestInfo.OrderId;

                    //异常时返回的业务系统着陆页面
                    var resultInterface = Builder.BuildSwiftPassWeChatPayResult();
                    var notifyInfo      = new PayNotifyInfo()
                    {
                        OrderId    = requestInfo.OrderId,
                        TradeNo    = "",
                        PaymentAmt = requestInfo.PaymentAmt.ToString(),
                        Result     = ((int)ResultStatus.Error).ToString(),
                    };
                    ViewBag.ReturnUrl = resultInterface.GetReturnUrl(requestInfo, notifyInfo);
                }
                catch (BizException bex)
                {
                    requestInfo.ResultDesc    = bex.Message;
                    requestInfo.ExecuteResult = (int)ResultStatus.Error;
                    PayRequestDAL.Update(requestInfo);

                    ViewBag.ErrorMsg = bex.Message;
                    return(View());
                }
                catch (Exception ex)
                {
                    requestInfo.ExecuteResult = (int)ResultStatus.Error;
                    requestInfo.ResultDesc    = ex.ToString();
                    PayRequestDAL.Update(requestInfo);
                    ViewBag.ErrorMsg = "系统执行时发生异常:" + ex.Message;
                    return(View());
                }
                #endregion

                //支付请求执行成功
                onlinePay.ExecuteSuccess(requestInfo);
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMsg = "系统执行时发生异常:" + ex.Message;
                string log = string.Format(@"WAP支付JSAPI发生异常!{0}异常描述:{1}{0}异常堆栈:{2}{0}请求参数:requestSysNo={3} code={4}",
                                           Environment.NewLine, ex.Message, ex.StackTrace, requestSysNo, code);
                LogWriter.WriteLog(log, AppConfig.Global.SwiftPassWeChatPayLogFolder, ExceptionHelper.ExceptionLevel.Exception);
            }
            return(View());
        }