Get the current user's Openid and precautions in a timely manner on the WeChat Official Account Development webpage

Source: Internet
Author: User
Tags openid
Preface this article is mainly post-article on webpage authorization for obtaining basic user information. it is also the first form of silent Authorization. when a user clicks a link in a public account, how to obtain the current user's OpenId again.

Preface

This article mainly undertakes the post-article on webpage authorization to obtain basic user information. it is also the first form of silent Authorization. when a user clicks the link in the public account, how to obtain the current user's OpenId again.

All the friends who have read the previous article know that the basic information of the user has been stored in the database when the user pays attention to it. if the user clicks the webpage link in the public account after a long time, how can we obtain the unique identifier again?


Obtain openid again

Implementation

First, we define a method for obtaining openid ReGetOpenId

Public static void ReGetOpenId () {string url = System. web. httpContext. current. request. url. absoluteUri; // Obtain the current url if (System. web. httpContext. current. session ["openid"] = "" | System. web. httpContext. current. session ["openid"] = null) {// you must first determine whether the if (System. web. httpContext. current. request. queryString ["code"] = "" | System. web. httpContext. current. request. queryString ["code"] = null) {// when the Code is null, obtain the Code string GetCodeUrls = GetCodeUrl (url); System. web. httpContext. current. response. redirect (GetCodeUrls); // jump to the server first. after obtaining the code, the server will jump back to this page.} else {// The Code is not empty. after obtaining the code, the server will jump back, now retrieve openid Log = new log (AppDomain. currentDomain. baseDirectory + @ "/log/Log.txt"); string openid = ""; openid = GetOauthAccessOpenId (System. web. httpContext. current. request. queryString ["Code"]); // obtain the user's openid System again. web. httpContext. current. session ["openid"] = openid ;}}}

Note: The url should preferably contain a domain name, and the domain name of the peanut shell won't work. when you call the platform interface, an incorrect link error will be reported.

The above GetCodeUrl method is as follows:

# Region re-obtains the Code jump link (only basic information can be obtained without user authorization )///Re-obtain the Code. in the future, Code will be taken back to the target page (only basic information (openid) can be obtained without user authorization ))///Target page///
 Public static string GetCodeUrl (string url) {string CodeUrl = ""; // Encode the url = System. web. httpUtility. urlEncode (url); CodeUrl = string. format ("https://open.weixin.qq.com/connect/oauth2/authorize? Appid = "+ Appid +" & redirect_uri = "+ url + "? Action = viewtest & response_type = code & scope = snsapi_base & state = 1 # wechat_redirect "); return CodeUrl;} # endregion

The GetOauthAccessOpenId method is as follows:

# Region exchange Code for the user's openid and access_token ///Obtain the user's openid and access_token based on the Code.Public static string GetOauthAccessOpenId (string code) {Log log = new Log (AppDomain. currentDomain. baseDirectory + @ "/log/Log.txt"); string Openid = ""; string url = "https://api.weixin.qq.com/sns/oauth2/access_token? Appid = "+ Appid +" & secret = "+ Secret +" & code = "+ code +" & grant_type = authorization_code "; string gethtml = MyHttpHelper. httpGet (url); log. log ("the url obtained is:" + url); log. log ("gethtml obtained is" + gethtml); OAuth_Token ac = new OAuth_Token (); ac = JsonHelper. toObject
 
  
(Gethtml); log. log ("Can I get openid =" + ac. openid from html); Openid = ac. openid; return Openid;} # endregion
 

You can obtain the user's Openid through the above method. as shown above, the user ID is saved in System. Web. HttpContext. Current. Session ["openid"], so it is very easy to get it.

Run

# Region obtain the current user's Openid ReGetOpenId (); log. log ("after obtaining the openid method, the current Session value is:" + System. web. httpContext. current. session ["openid"]); # endregion

Note: The OAuth_Token class is as follows:

Public class OAuth_Token {////// Webpage authorization interface call credential. note: This access_token is different from the access_token supported by IoT platform ///Public string access_token {get; set ;}////// Access_token interface call credential timeout time, in seconds )///Public string expires_in {get; set ;}////// Refresh access_token ///Public string refresh_token {get; set ;}////// Unique user id. Note that when a user does not pay attention to a public account, a unique OpenID is generated when the user accesses the webpage of the public account ///Public string openid {get; set ;}////// User authorization scope ///Public string scope {get; set ;}}

Log files

The simple log classes used are also provided by the way:

////// Log class ///Public class Log {private string logFile; private StreamWriter writer; private FileStream fileStream = null; public Log (string fileName) {logFile = fileName; CreateDirectory (logFile );} public void log (string info) {try {System. IO. fileInfo fileInfo = new System. IO. fileInfo (logFile); if (! FileInfo. exists) {fileStream = fileInfo. create (); writer = new StreamWriter (fileStream);} else {fileStream = fileInfo. open (FileMode. append, FileAccess. write); writer = new StreamWriter (fileStream);} writer. writeLine (DateTime. now + ":" + info);} finally {if (writer! = Null) {writer. close (); writer. dispose (); fileStream. close (); fileStream. dispose () ;}} public void CreateDirectory (string infoPath) {DirectoryInfo directoryInfo = Directory. getParent (infoPath); if (! DirectoryInfo. Exists) {directoryInfo. Create ();}}}

The call method is as follows:

Log log = new Log (AppDomain. CurrentDomain. BaseDirectory + @ "/log/Log.txt"); log. log ("I will be entered in the Log file ")

Finally, you can obtain other basic information of the current user from the database. This helps you complete other business modules in your project.

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.