微信公眾號開發之網頁中及時獲取當前用戶Openid及注意事項


目錄

(一)微信公眾號開發之VS遠程調試
(二)微信公眾號開發之基礎梳理
(三)微信公眾號開發之自動消息回復和自定義菜單
(四)微信公眾號開發之網頁授權獲取用戶基本信息
(五)微信公眾號開發之網頁中及時獲取當前用戶Openid及注意事項
(六)微信公眾號開發之掃碼支付
(七)微信公眾號開發之公眾號支付
(八)微信公眾號開發之現金紅包
(九)微信公眾號開發之回復圖文消息(被動)

前言

這篇主要是承接上篇的網頁授權獲取用戶基本信息的后文,也是對第一種靜默授權之后,用戶點擊公眾號內鏈接時,如何再次取得當前用戶的OpenId的大致講解和一些注意事項。

 

看過上一篇的小伙伴都知道,我們在用戶關注的時候就已經將該用戶的基本信息存入數據庫中,那么如果該用戶過了很久才點擊公眾號內的網頁鏈接,那么我們該如何再次獲取這個唯一標識呢?

重新獲取openid

具體實現

首先,我們定一個獲取openid的方法 ReGetOpenId

public static void ReGetOpenId()
        {
            string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;//獲取當前url
            if (System.Web.HttpContext.Current.Session["openid"] == "" || System.Web.HttpContext.Current.Session["openid"] == null)
            {
                //先要判斷是否是獲取code后跳轉過來的
                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);//先跳轉到微信的服務器,取得code后會跳回來這頁面的

                }
                else
                {
                    //Code非空,已經獲取了code后跳回來啦,現在重新獲取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最好是帶域名的,花生殼的域名是行不通的,再調微信平台接口的時候,會報鏈接不正確錯誤

上文中GetCodeUrl方法如下

     #region 重新獲取Code的跳轉鏈接(沒有用戶授權的,只能獲取基本信息)
        /// <summary>重新獲取Code,以后面實現帶着Code重新跳回目標頁面(沒有用戶授權的,只能獲取基本信息(openid))</summary>
        /// <param name="url">目標頁面</param>
        /// <returns></returns>
        public static string GetCodeUrl(string url)
        {
            string CodeUrl = "";
            //對url進行編碼
            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

 

上文中 GetOauthAccessOpenId方法如下

     #region 以Code換取用戶的openid、access_token
        /// <summary>根據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

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

在需要獲取的地方執行

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

注:上文中 OAuth_Token 類如下:

 

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

 

因為無法使用一般的url,所以是把程序部署在服務器上,無法進行調試,只有打印日志查看效果,最后點擊鏈接,日志如下:

日志文件

用到的簡單日志類也順便提供放上來:

/// <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();
            }
        }
    }

調用呢,很簡單,調用方法如下:

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

 

最后呢,拿到當前用戶Openid,就可以從數據庫再次獲取到該用戶的其他基本信息。從而可以更好的輔助你完成你項目中其他的業務模塊。

 

未完待續,持續填坑中。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM