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 2 {3 3 4 4 // GET:/ApplyVIP/5 5 6 6 public ActionResult Index (string url) 7 7 {8 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 9 WeiXin. appid, 10 10 url, // callback page URL11 11 Guid. newGuid (). toString ("N"); 12 12 return Redirect (_ url); // The callback page URL is automatically retrieved and redirected to the page 13} to which the url belongs}
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.

1 // controller 2 public string GetOpenId () {3 string code = requset. querystring ["code"]; 4 string openid = ""; 5 string json = ""; 6 string url = string. format ("https://api.weixin.qq.com/sns/oauth2/access_token? Appid = {0} & secret = {1} & code = {2} & grant_type = authorization_code "// use appid, appaseret, code 7, WeiXin. appid, WeiXin. aseret, code); 8 HttpQuery. get (url, null, msg => {9 json = msg; 10}); 11 JObject job = (JObject) JsonConvert. deserializeObject (json); 12 openid = job ["openid"]. toString (); 13 return openid; 14}
Obtain openID

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

1 public class HttpQuery {2 private static readonly string DefaultUserAgent = 3 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1 ;. net clr 1.1.4322 ;. net clr 2.0.50727) "; 4 5 public static void Get (string url, object data, Action <string> callback) {6 IDictionary <string, string> parameters = Getparameters (data ); 7 8 if (! (Parameters = null | parameters. Count = 0) {9 url + = "? "; 10 foreach (var item in parameters) {11 url + = item. key + "=" + item. value + "&"; 12} 13} 14 CreateGetHttpResponse (url, null, callback ); 15} 16 // <summary> 17 // create a get http request 18 /// </summary> 19 /// <param name = "url"> request URL </param> 20 /// <param name = "timeout"> request timeout </param> 21 /// <param name = "userAgent"> client browser information, it can be blank </param> 22 // <param name = "cookies"> Cookie information sent along with the HTTP request, such If no authentication is required, it can be blank </param> 23 // <returns> </returns> 24 private static HttpWebResponse CreateGetHttpResponse (string url, int? Timeout, string userAgent, 25 CookieCollection cookies, Action <string> callback, string encoding = "UTF-8") {26 if (string. isNullOrEmpty (url) {27 return null; 28 // throw new ArgumentNullException ("url"); 29} 30 try {31 HttpWebRequest request = WebRequest. create (url) as HttpWebRequest; 32 request. method = "GET"; 33 request. userAgent = DefaultUserAgent; 34 if (! String. isNullOrEmpty (userAgent) {35 request. userAgent = userAgent; 36} 37 if (timeout. hasValue) {38 request. timeout = timeout. value; 39} 40 if (cookies! = Null) {41 request. cookieContainer = new CookieContainer (); 42 request. cookieContainer. add (cookies); 43} 44 45 HttpWebResponse httpWebResponse = request. getResponse () as HttpWebResponse; 46 47 StreamReader reader = new StreamReader (httpWebResponse. getResponseStream (), 48 System. text. encoding. getEncoding (encoding); 49 50 string html = ""; 51 // obtain the requested data 52 html = reader. readToEnd (); 53 // disable 54 httpWebResponse. close (); 55 reader. close (); 56 57 callback (html); 58 return httpWebResponse; 59} 60} catch {61 callback (null); 62} 63 return null; 64} 65 66}
Http GET request

 

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.