溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

微信公眾號(hào)開(kāi)發(fā)網(wǎng)頁(yè)中如何獲取當(dāng)前用戶Openid

發(fā)布時(shí)間:2021-09-10 14:32:58 來(lái)源:億速云 閱讀:121 作者:小新 欄目:移動(dòng)開(kāi)發(fā)

這篇文章主要介紹了微信公眾號(hào)開(kāi)發(fā)網(wǎng)頁(yè)中如何獲取當(dāng)前用戶Openid,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

具體實(shí)現(xiàn)

首先,我們定一個(gè)獲取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)過(guò)來(lái)的
                if (System.Web.HttpContext.Current.Request.QueryString["code"] == "" || System.Web.HttpContext.Current.Request.QueryString["code"] == null)
                {
                    //Code為空時(shí),先獲取Code
                    string GetCodeUrls = GetCodeUrl(url);
                    System.Web.HttpContext.Current.Response.Redirect(GetCodeUrls);//先跳轉(zhuǎn)到微信的服務(wù)器,取得code后會(huì)跳回來(lái)這頁(yè)面的

                }
                else
                {
                    //Code非空,已經(jīng)獲取了code后跳回來(lái)啦,現(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;
                }
            }
        }

注:url最好是帶域名的,花生殼的域名是行不通的,再調(diào)微信平臺(tái)接口的時(shí)候,會(huì)報(bào)鏈接不正確錯(cuò)誤

上文中GetCodeUrl方法如下

#region 重新獲取Code的跳轉(zhuǎn)鏈接(沒(méi)有用戶授權(quán)的,只能獲取基本信息)
        /// <summary>重新獲取Code,以后面實(shí)現(xiàn)帶著Code重新跳回目標(biāo)頁(yè)面(沒(méi)有用戶授權(quán)的,只能獲取基本信息(openid))</summary>
        /// <param name="url">目標(biāo)頁(yè)面</param>
        /// <returns></returns>
        public static string GetCodeUrl(string url)
        {
            string CodeUrl = "";
            //對(duì)url進(jìn)行編碼
            url = System.Web.HttpUtility.UrlEncode(url);
            CodeUrl = string.Format("https://open.weixin.qq.com/connect/oauth3/authorize?appid=" + Appid + "&redirect_uri=" + url + "?action=viewtest&response_type=code&scope=snsapi_base&state=1#wechat_redirect");

            return CodeUrl;

        }
        #endregion

上文中 GetOauthAccessOpenId方法如下

#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/oauth3/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

通過(guò)以上方法即可拿到用戶的Openid,如上文所示,用戶id保存在System.Web.HttpContext.Current.Session["openid"]  中,所以獲取也是非常簡(jiǎn)單

在需要獲取的地方執(zhí)行

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

注:上文中 OAuth_Token 類(lèi)如下:

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

日志文件

用到的簡(jiǎn)單日志類(lèi)也順便提供放上來(lái):

/// <summary>
    /// 日志類(lèi)
    /// </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();
            }
        }
    }

調(diào)用呢,很簡(jiǎn)單,調(diào)用方法如下:

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

最后呢,拿到當(dāng)前用戶Openid,就可以從數(shù)據(jù)庫(kù)再次獲取到該用戶的其他基本信息。從而可以更好的輔助你完成你項(xiàng)目中其他的業(yè)務(wù)模塊。

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“微信公眾號(hào)開(kāi)發(fā)網(wǎng)頁(yè)中如何獲取當(dāng)前用戶Openid”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI