国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home WeChat Applet WeChat Development Timely obtain the current user Openid and precautions in the WeChat public account development webpage

Timely obtain the current user Openid and precautions in the WeChat public account development webpage

Feb 24, 2017 pm 05:01 PM
WeChat public account development

Preface

This article mainly follows the previous article's web page authorization to obtain the user's basic information. It is also about how to obtain the current user again when the user clicks on the link in the official account after the first silent authorization. A general explanation of OpenId and some precautions.

Everyone who has read the previous article knows that we have already stored the user’s basic information in the database when the user pays attention, so if the user waits for a long time Click on the web link in the official account, so how do we obtain this unique identifier again?


Re-obtain openid

Specific implementation

First, we define a method to obtain openid ReGetOpenId

public static void ReGetOpenId()
        {
            string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;//獲取當(dāng)前url
            if (System.Web.HttpContext.Current.Session["openid"] == "" || System.Web.HttpContext.Current.Session["openid"] == null)
            {
                //先要判斷是否是獲取code后跳轉(zhuǎn)過來的
                if (System.Web.HttpContext.Current.Request.QueryString["code"] == "" || System.Web.HttpContext.Current.Request.QueryString["code"] == null)
                {
                    //Code為空時,先獲取Code
                    string GetCodeUrls = GetCodeUrl(url);
                    System.Web.HttpContext.Current.Response.Redirect(GetCodeUrls);//先跳轉(zhuǎn)到微信的服務(wù)器,取得code后會跳回來這頁面的

                }
                else
                {
                    //Code非空,已經(jīng)獲取了code后跳回來啦,現(xiàn)在重新獲取openid
                    Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
                    string openid = "";
                    openid = GetOauthAccessOpenId(System.Web.HttpContext.Current.Request.QueryString["Code"]);//重新取得用戶的openid
                    System.Web.HttpContext.Current.Session["openid"] = openid;
                }
            }
        }

Note : It is best to have a domain name in the url. The domain name of the peanut shell will not work. When adjusting the WeChat platform interface, an incorrect link error will be reported

The GetCodeUrl method above is as follows

#region 重新獲取Code的跳轉(zhuǎn)鏈接(沒有用戶授權(quán)的,只能獲取基本信息)
        /// <summary>重新獲取Code,以后面實現(xiàn)帶著Code重新跳回目標(biāo)頁面(沒有用戶授權(quán)的,只能獲取基本信息(openid))</summary>
        /// <param name="url">目標(biāo)頁面</param>
        /// <returns></returns>
        public static string GetCodeUrl(string url)
        {
            string CodeUrl = "";
            //對url進(jìn)行編碼
            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 above is as follows

#region 以Code換取用戶的openid、access_token
        /// <summary>根據(jù)Code獲取用戶的openid、access_token</summary>
        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("拿到的url是:" + url);
            log.log("獲取到的gethtml是" + gethtml);
            OAuth_Token ac = new OAuth_Token();
            ac = JsonHelper.ToObject<OAuth_Token>(gethtml);
            log.log("能否從html里拿到openid=" + ac.openid);
            Openid = ac.openid;
            return Openid;
        }
        #endregion

You can get the user's Openid through the above method. As shown above, the user id is stored in System.Web.HttpContext.Current.Session["openid"], so get it It is also very simple

Execute where you need to obtain it

#region 獲取當(dāng)前用戶Openid
                ReGetOpenId();
                log.log("走完獲取openid的方法之后,當(dāng)前Session的值是:" + System.Web.HttpContext.Current.Session["openid"]);
                #endregion

Note: The OAuth_Token class mentioned above is as follows:

public class OAuth_Token
    {
        /// <summary>
        /// 網(wǎng)頁授權(quán)接口調(diào)用憑證,注意:此access_token與基礎(chǔ)支持的access_token不同
        /// </summary>
        public string access_token { get; set; }
        /// <summary>
        /// access_token接口調(diào)用憑證超時時間,單位(秒)
        /// </summary>
        public string expires_in { get; set; }
        /// <summary>
        /// 用戶刷新access_token
        /// </summary>
        public string refresh_token { get; set; }
        /// <summary>
        /// 用戶唯一標(biāo)識,請注意,在未關(guān)注公眾號時,用戶訪問公眾號的網(wǎng)頁,也會產(chǎn)生一個用戶和公眾號唯一的OpenID
        /// </summary>
        public string openid { get; set; }
        /// <summary>
        /// 用戶授權(quán)作用域
        /// </summary>
        public string scope { get; set; }
    }

Log file

The simple log class used is also provided by the way:

/// <summary>
    /// 日志類
    /// </summary>
    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 is very simple. The calling method is as follows:

     Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
        log.log("我會被輸入在日志文件中")

Finally, get the current user Openid, and then Other basic information about the user can be obtained from the database again. This can better assist you in completing other business modules in your project.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)