Home  >  Article  >  WeChat Applet  >  WeChat public platform development Session processing

WeChat public platform development Session processing

高洛峰
高洛峰Original
2017-03-06 09:12:301807browse

In the WeChat window, the input information is limited, and we need to request some information multiple times.

For example: when binding users, we need to enter relevant information of the user, such as: user name, password, or name, phone number, and if the server side is verified, the System users are bound to WeChat users.

Then, this WeChat account will have certain functional permissions, and you can check points, consumption records, etc. Service account: China Merchants Bank credit card has many functions.

The WeChat client cannot cache information, and the input information is limited. It needs to make multiple requests and save the current session status on the server. This requires Session.

This article takes user authentication and account binding as an example to illustrate the specific processing.

1. Create a general Session processing mechanism.

In order to better explain the principle and facilitate expansion, we will design the Session ourselves. Of course, System.Web.SessionState.HttpSessionState can also be used here, which is a commonly used Session mechanism on the Web.

1. Custom Session

is used to store session fragments and related data.

class Session
    {
        /// <summary>
        /// 缓存hashtable
        /// </summary>
        private static Hashtable mDic = new Hashtable();
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        public static void Add(string key, object value)
        {
            mDic[key] = value;
        }
        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="key">key</param>
        public static void Remove(string key)
        {
            if (Contains(key))
            {
                mDic.Remove(key);
            }
        }
        /// <summary>
        /// 设置值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set(string key, object value)
        {
            mDic[key] = value;
        }
        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object Get(string key)
        {
            return mDic[key];
        }
        /// <summary>
        /// 是否含有
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>bool</returns>
        public static bool Contains(string key)
        {
            return mDic.ContainsKey(key);
        }
        /// <summary>
        /// 清空所有项
        /// </summary>
        public static void Clear()
        {
            mDic.Clear();
        }
    }

2. Operation type

Record the specific operation type and identify the specific operation of the current session

/// 631fb227578dfffda61e1fa4d04b7d25
    /// 操作类型
    /// 039f3e95db2a684c7b74365531eb6044
    enum Operation
    {
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 认证
        /// 039f3e95db2a684c7b74365531eb6044
        Auth,
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 添加用户
        /// 039f3e95db2a684c7b74365531eb6044
        CreateUser
    }

3. Operation process enumeration

is used to identify the current operation and which stage it is in. Different processes are performed at different stages.

/// 631fb227578dfffda61e1fa4d04b7d25
    /// 操作过程
    /// 039f3e95db2a684c7b74365531eb6044
    enum OperationStage
    {
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 默认
        /// 039f3e95db2a684c7b74365531eb6044
        Default,
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 第一步
        /// 039f3e95db2a684c7b74365531eb6044
        First,
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 第二步
        /// 039f3e95db2a684c7b74365531eb6044
        Second,
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 第三步
        /// 039f3e95db2a684c7b74365531eb6044
        Third
    }

4. Session cache item

Cache record item, which records the operation type, operation steps and session object. In order to facilitate session management, the last access time and whether to automatically clear the logo are also added.

class SessionItem
    {
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 操作类型
        /// 039f3e95db2a684c7b74365531eb6044
        public Operation Oper { get; set; }
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 当前步骤
        /// 039f3e95db2a684c7b74365531eb6044
        public OperationStage Stage { get; set; }
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 数据对象
        /// 039f3e95db2a684c7b74365531eb6044
        public object Data { get; set; }
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 是否自动删除
        /// 039f3e95db2a684c7b74365531eb6044
        public bool AutoRemove
        {
            get;
            set;
        }
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 最后更新时间
        /// 039f3e95db2a684c7b74365531eb6044
        public DateTime UpdateTime { get; set; }
    }

Second, we need to add Session processing to the message processing.

1. Add cache item data object

This object records the relevant information entered by the user during the session. It is also used as an object for business processing data.

class AuthSessionItem
    {
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 用户名
        /// 039f3e95db2a684c7b74365531eb6044
        public string FromUserName { get; set; }
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 账号
        /// 039f3e95db2a684c7b74365531eb6044
        public string Code { get; set; }
        /// 631fb227578dfffda61e1fa4d04b7d25
        /// 唯一标识
        /// 039f3e95db2a684c7b74365531eb6044
        public string ID { get; set; }
    }

2. Authentication processing process

1) Start entering the authentication, identify according to the authentication keyword, and start session, and cache relevant data

2) Prompt to enter personal account information

3) WeChat users enter personal account, the server records the account information, and prompts to enter employee card number

4) The WeChat user enters the card number information, the server records the card number information, and calls the specific authentication logic

5) The user passes the authentication, binds the WeChat OpenId, prompts for successful binding information, and clears the session.

During the authentication process, the legality of user input information needs to be verified, and during the session, the user is supported to exit the current operation.

/// 631fb227578dfffda61e1fa4d04b7d25
        /// 认证用户信息
        /// 039f3e95db2a684c7b74365531eb6044
        /// 48c89b85c0dea34386a1ce7621016c778bb7487ae6a16a43571bc14c7fcf93c2
        /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3
        private bool Auth(TextMessage tm, ref string response)
        {
            SessionItem sessionItem = null;
            if (string.Equals(tm.Content, "Auth", StringComparison.OrdinalIgnoreCase))
            {
                //检查是否已经认证,业务组件验证
                if (UserManager.IsAuth(tm.FromUserName))
                {
                    //如果已经认证,提示
                    tm.Content = "您已经认证过了,无需再次认证!";                    
                }
                else
                {
                    AuthSessionItem authSessionItem = new AuthSessionItem();
                    authSessionItem.FromUserName = tm.FromUserName;

                    sessionItem.Oper = Operation.Auth;
                    sessionItem.Stage = OperationStage.First;
                    sessionItem.Data = authSessionItem;
                    Session.Set(tm.FromUserName, sessionItem);

                    //输入账号,并将数据和步骤,写入缓存
                    tm.Content = "请输入您的个人账号";
                }

                response = ResponseText(tm);
                return false;
            }

            //从Session获取用户信息
            sessionItem = Session.Get(tm.FromUserName) as SessionItem;
            //如果会话存在,且当前操作为用户认证
            if (sessionItem != null && sessionItem.Oper == Operation.Auth)
            {
                if (sessionItem.Stage == OperationStage.First)
                {
                    tm.Content = tm.Content.Trim();
                    if (string.IsNullOrEmpty(tm.Content) || tm.Content.Length > 20)
                    {
                        tm.Content = "输入的个人账号不合法,请重新输入。";
                        response = ResponseText(tm);
                        return false;
                    }
                    AuthSessionItem authSessionItem = sessionItem.Data as AuthSessionItem;
                    if (authSessionItem != null)
                    {
                        authSessionItem.Code = tm.Content;
                    }

                    //更新缓存
                    sessionItem.Stage = OperationStage.Second;
                    Session.Set(tm.FromUserName, sessionItem);
                    tm.Content = "请输入您的员工卡号!\n退出认证请输入Exit。";
                    response = ResponseText(tm);  
                }
                else if (sessionItem.Stage == OperationStage.Second)
                {
                    string cardNum = null;
                    if (!Common.TryConvertToCardNum(tm.Content, out cardNum))
                    {                       
                        tm.Content = "员工卡号不合法,请重新输入。\n退出认证请输入Exit。";
                        response = ResponseText(tm);
                        return false;
                    }
                    AuthSessionItem authSessionItem = sessionItem.Data as AuthSessionItem;
                    if (authSessionItem != null)
                    {
                        authSessionItem.ID = cardNum;
                    }
                    //认证
                    string message;
                    if (UserManager.Authenticate(authSessionItem, out message))
                    {
                        tm.Content = "祝贺您,已经认证成功,可以使用通讯录的查询功能呢。";
                        //清理缓存
                        Session.Remove(tm.FromUserName);
                        response = ResponseText(tm);
                        return true;
                    }
                    else if (!string.IsNullOrEmpty(message))
                    {
                        tm.Content = message;
                    }
                    else
                    {
                        tm.Content = "您输入的信息有误。\n重新认证请输入:Auth!";
                    }
                    //过程结束:清理Session
                    Session.Remove(tm.FromUserName);
                    response = ResponseText(tm);
                    return false;
                }
            }

            return false;
        }

3. Exit the session and clean up the Session

During the authentication process, the user can forcefully exit the current operation through commands. After exiting the current During operation, session information needs to be cleared.

/// 631fb227578dfffda61e1fa4d04b7d25
        /// 退出,并清理Session
        /// 039f3e95db2a684c7b74365531eb6044
        /// 48c89b85c0dea34386a1ce7621016c778bb7487ae6a16a43571bc14c7fcf93c2
        /// ac0426a4c30f960f93a3daeaf71812178bb7487ae6a16a43571bc14c7fcf93c2
        /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3
        private bool Exit(TextMessage tm, ref string response)
        {
            //退出
            if (string.Equals(tm.Content, "Exit", StringComparison.OrdinalIgnoreCase))
            {
                //清除Session
                Session.Remove(tm.FromUserName);
                tm.Content = "您已退出当前操作,请执行其他操作。";
                response = ResponseText(tm);
                return true;
            }

            return false;
        }

3. User authentication passed, binding WeChat account

User authentication passed, and binding WeChat OpenId, you can query through OpenId Address book, query personal points and consumption records and other operations. User authentication is an identity authentication process and a user binding process. If the user identity is authenticated, you can query specific information through your WeChat account. At this time, the business layer can directly query user-related information based on the OpenId assigned by WeChat.

4. Postscript

Through this method, public accounts can realize more and more complex business applications through small text input boxes. Of course, it is more intuitive and convenient to enter information by providing a web page.

For more articles related to WeChat public platform development and Session processing, please pay attention to the PHP Chinese website!

Statement:
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