Obtaining OPENID based on ASP.NET MVC Wechat Web Logon Authorization (scope is snsapi_base) process

Keywords: ASP.NET Session encoding JSON

Flow chart

 

First, we need to define a global OPENID which is similar to the current login user ID of the ordinary account password login system, because I am the MVC framework. Here, I define a controller base class BaseController and then define OPENID in BaseController.

 1  public class BaseController : Controller
 2     {
 3         public string openid
 4         {
 5             get {
 6                 return Session["openid"].ToString();
 7             }
 8             set {
 9                 Session["openid"] = value;
10             }
11         }
12 
13     }

Then define a HomeController and write a test login function

 1     public class HomeController : BaseController
 2     {
 3         // GET: Home
 4         public ActionResult Login()
 5         {
 6             if (string.IsNullOrEmpty(openid)) //openid No jump authorization exists
 7             {
 8                 //100,000 lines of authorization-related code are ignored here
 9             }
10             //Ignore 3000 rows for user information correlation here
11             return View();
12         }
13     }

The above is a Weichat Authorization Logon Function Code which ignores most of the irrelevant codes. Of course, many people don't want these. Next is some more detailed codes, which can be divided into two big modules.

  1. Get OPENID
  2. Getting User Information

Here I write these two modules as two methods defined in the WXHelper class

    public class WXHelper {
        public string GetOpenID() {
            return "openid";
        }
        public User_UserInfo GetUserInfo() {
            User_UserInfo model_UserInfo = new User_UserInfo();

            return model_UserInfo;
        }
    }

 

Then the previous Login Action can be changed to this

        public ActionResult Login()
        {
            if (string.IsNullOrEmpty(openid)) //openid No jump authorization exists
            {
                openid = WXHelper.GetOpenID();
            }
            //LoginUserInfo It's my current login user information. You can find your own way to save it. Session Or global variables or something like that
            LoginUserInfo = WXHelper.GetUserInfo();
            return View();
        }

Let's start implementing the first method, GetOpenID. Official API

I won't say much about the specific request here.

Because the callback address can not be written to the local address for debugging, I use manual record code and manually write code to the local code during the validity period to continue debugging.

Reluctantly paste code

        /// <summary>
        /// Obtain code Method
        /// </summary>
        private static void GetWeChat_Code()
        {
            string urlhead = "https://";
            string rediretUrl = "https%3a%2f%2fxxxx.com%2fHome%2fLoadCode";
            string strUrl = $"{urlhead}open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={rediretUrl}&response_type=code&scope=snsapi_base&state=qwe12e12e#wechat_redirect";
            //Omit here n That's ok get Request method
        }    

 

Careful friends may find that the redireUrl address above points to LoadCode under the Home Controller, the method SO

       #region Wechat Authorized Callback
        public ActionResult LoadCode(string code, string state)
        {
            return View();
        }
        #endregion

 

Because of the parameter mapping of MVC, I just need to write code and state as method parameters, so here I can get the code method, and then we can get OPENID directly through code.

        #region Obtain OpenID

        public static string GetOpenId(string code)
        {
            string urlhead = "https://";
            string strUrl = $"{urlhead}api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code";
            Access_openid token = new Access_openid();
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl);  //use GET Formal request specified address 
            req.Method = "GET";

            using (WebResponse wr = req.GetResponse())
            {
                //HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();  
                StreamReader reader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();

                //Right here. Access_token assignment  
                token = JsonConvert.DeserializeObject<Access_openid>(content);
            }
            return token.openid;
        }

        #endregion

 

If somebody is confused about this Access_openid object, let's say that this object is the object of JSON data obtained by the red box in the figure below. Here we are snsapi_base, so we just need openid to cut the whole authorization process to the end.

Posted by zoobooboozoo on Wed, 26 Dec 2018 12:24:07 -0800