MVC WeChat development to get the user's OpenID, mvc to get the user's openid

Source: Internet
Author: User
Tags openid

Obtain the user's OpenID through MVC development, and obtain the user's openid through mvc

 

 

The first development version of the web page, the most important to obtain the OpenId, is hereby recorded

1. First, you must have appid and appsecret.

 1 1.    public class WeiXin {
 2 
 3         public static string appid {
 4             get {
 5                 string _appid = "wx3xxxxxxxxxxxxxxx";
 6                 return _appid;
 7             }
 8         }
 9         public static string aseret {
10             get {
11                 string appsecret = "b6719276d539796d94bxxxxxxxxxxxxxxx";
12                 return appsecret;
13             }
14         }
15 
16 }
Prepare appid and appsecret

2. only the user's openID is obtained. After the service number obtains the advanced interface, by default, snsapi_base and snsapi_userinfo in the scope parameter are available. The attacker is guided to open the following page and use snsapi_base as the webpage authorization initiated by scope. The authorization is silent and automatically redirected to the callback page. The user is aware that the callback page is directly entered (the url parameter in the code below is the callback page, which can be statically written as: string url = https://wx.baidu.com/controller/getopenid,#url#enter httputility.urlencode, the domain name on the callback page must be the same as the callback domain name set in the public account)

1 public class ApplyVIPController: Controller
  2     {
  3
  4 // GET: / ApplyVIP /
  5
  6 public ActionResult Index (string url)
  7 {
  8 string _url = string.Format ("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect",
  9 WeiXin.appid,
10 url, // callback page URL
11 Guid.NewGuid (). ToString ("N"));
12 return Redirect (_url); // Here will automatically fetch the callback page URL, and jump to the page to which the url belongs
13}
Silent authorization and jump to the callback page

3. obtain the code and use the code to obtain the Openid. If the code is correct, the returned JSON data packet is: {"access_token": "ACCESS_TOKEN", "expires_in": 7200, "refresh_token": "REFRESH_TOKEN ", "openid": "OPENID", "scope": "SCOPE"}, which includes the required OPENID.

// controller
  public string GetOpenId () {
             string code = requset.querystring ["code"];
             string openid = "";
             string json = "";
             string url = string.Format ("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code" // AppID, appaseret, code
     , WeiXin.appid, WeiXin.aseret, code);
             HttpQuery.Get (url, null, msg => {
                 json = msg;
             });
             JObject job = (JObject) JsonConvert.DeserializeObject (json);
             openid = job ["openid"]. ToString ();
             return openid;
         }
View Code

4. Request to obtain the httpquery. get () method of Openid

public class HttpQuery {
        private static readonly string DefaultUserAgent =
            "Mozilla / 4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

        public static void Get (string url, object data, Action <string> callback) {
            IDictionary <string, string> parameters = Getparameters (data);

            if (! (parameters == null || parameters.Count == 0)) {
                url + = "?";
                foreach (var item in parameters) {
                    url + = item.Key + "=" + item.Value + "&";
                }
            }
            CreateGetHttpResponse (url, null, null, null, callback);
        }
        /// <summary>
        /// Create a GET HTTP request
        /// </ summary>
        /// <param name = "url"> URL requested </ param>
        /// <param name = "timeout"> timeout of the request </ param>
        /// <param name = "userAgent"> the requested client browser information can be empty </ param>
        /// <param name = "cookies"> The cookie information sent along with the HTTP request can be empty if authentication is not required </ param>
        /// <returns> </ returns>
        private static HttpWebResponse CreateGetHttpResponse (string url, int? timeout, string userAgent,
            CookieCollection cookies, Action <string> callback, string encoding = "utf-8") {
            if (string.IsNullOrEmpty (url)) {
                return null;
                // throw new ArgumentNullException ("url");
            }
            try {
                HttpWebRequest request = WebRequest.Create (url) as HttpWebRequest;
                request.Method = "GET";
                request.UserAgent = DefaultUserAgent;
                if (! string.IsNullOrEmpty (userAgent)) {
                    request.UserAgent = userAgent;
                }
                if (timeout.HasValue) {
                    request.Timeout = timeout.Value;
                }
                if (cookies! = null) {
                    request.CookieContainer = new CookieContainer ();
                    request.CookieContainer.Add (cookies);
                }

                HttpWebResponse httpWebResponse = request.GetResponse () as HttpWebResponse;

                StreamReader reader = new StreamReader (httpWebResponse.GetResponseStream (),
                    System.Text.Encoding.GetEncoding (encoding));

                string html = "";
                // Get the requested data
                html = reader.ReadToEnd ();
                //shut down
                httpWebResponse.Close ();
                reader.Close ();
      
                    callback (html);
                    return httpWebResponse;
                }
            } catch {
                callback (null);
            }
            return null;
        }

} 
View Code

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.