public ActionResult Index(int Lid=1) { if (Request.QueryString["code"] == null) { if (Session["UId"] == null) { Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AppID + "&redirect_uri=******" + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"); } else { ProductService productService = new ProductService(); //获取5个景点以及2个套票 var list = productService.GetLiLingProduct(); return View(list); } return View(); } else { ELYG.Dealer.Common.Log.Info(this.GetType().ToString(), "获取授权" + DateTime.Now); //如果不为空 则是授权页面跳转 获取用户信息 保存到数据库 string code = Request.QueryString["code"].ToString(); #region 获取access_token 以及用户openid string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppID + "&secret=" + AppSecret + "&code=" + code + "&grant_type=authorization_code"; string response = HttpGet(url); JavaScriptSerializer json = new JavaScriptSerializer(); //实例化一个能够序列化数据的类 ToJson list = json.Deserialize<ToJson>(response); //将json数据转化为对象类型并赋值给list ELYG.Dealer.Common.Log.Info(this.GetType().ToString(), "获取access_token 以及用户openid" + DateTime.Now+"openid="+list.openid); #endregion 获取access_token 以及用户openid Session["UId"] = list.openid; //#region 根据access_token 以及用户openid 获取用户详细信息 string url2 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + list.access_token + "&openid=" + list.openid + "&lang=zh_CN"; string Openresponse = HttpGet(url2); WxUser wxUser = json.Deserialize<WxUser>(Openresponse); //将json数据转化为对象类型并赋值给list //#endregion 根据access_token 以及用户openid 获取用户详细信息 ELYG.Dealer.Common.Log.Info(this.GetType().ToString(), "根据access_token 以及用户openid 获取用户详细信息" + DateTime.Now +" "+ Openresponse); // UserService userService = new UserService(); //var users= userService.GetList().Where(p => p.openId == list.openid).FirstOrDefault(); // if (users==null) // { // user u = new user(); // u.openId = list.openid; // userService.Insert(u); // ELYG.Dealer.Common.Log.Info(this.GetType().ToString(), "添加用户信息" + DateTime.Now + " " + Openresponse); // } ProductService productService = new ProductService(); //获取5个景点以及2个套票 var lists = productService.GetLiLingProduct(); return View(lists); } }
如上代码
HomeController: 获取授权2018/12/12 15:28:27
HomeController: 获取access_token 以及用户openid2018/12/12 15:28:27openid=oIqWS1RcRd1bo-kdg3gUROn17P5M 2018-12-12 15:28:27.721
HomeController: 根据access_token 以及用户openid 获取用户详细信息2018/12/12 15:28:27
{"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest hint: [sRE1oa07074696!]"}