SoFunction
Updated on 2025-03-09

WeChat public platform development tutorial (8) Session handling problems

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

For example: When binding a user, we need to enter the user's relevant information, such as: user name, password, or name or phone number, and the server verification is passed, and the system user can be bound to the WeChat user.

Then, this WeChat account has certain functional permissions, which can check points, consumption records, etc. Service number: China Merchants Bank Credit Card has many functions.

The WeChat client cannot cache information, and the input information is limited, so multiple requests are required to save the current session status on the server. This requires a Session.

This article uses user authentication and binding accounts as an example to illustrate the specific processing.

1. Create a general Session processing mechanism.

In order to better explain the principles and facilitate expansion, we will design our own Session. Of course, it can also be used here, this is a commonly used Session mechanism on the Web.

1. Custom Session

Used to store session fragments and related data.

class Session
  {
    /// <summary>
    /// Cache hashtable    /// </summary>
    private static Hashtable mDic = new Hashtable();
    /// <summary>
    /// Add to    /// </summary>
    /// <param name="key">key</param>
    /// <param name="value">value</param>
    public static void Add(string key, object value)
    {
      mDic[key] = value;
    }
    /// <summary>
    /// Remove    /// </summary>
    /// <param name="key">key</param>
    public static void Remove(string key)
    {
      if (Contains(key))
      {
        (key);
      }
    }
    /// <summary>
    /// Set value    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    public static void Set(string key, object value)
    {
      mDic[key] = value;
    }
    /// <summary>
    /// Get the value    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static object Get(string key)
    {
      return mDic[key];
    }
    /// <summary>
    /// Whether it contains    /// </summary>
    /// <param name="key">key</param>
    /// <returns>bool</returns>
    public static bool Contains(string key)
    {
      return (key);
    }
    /// <summary>
    /// Clear all items    /// </summary>
    public static void Clear()
    {
      ();
    }
  }

2. Operation type

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

/// <summary>
  /// Operation type  /// </summary>
  enum Operation
  {
    /// <summary>
    /// Certification    /// </summary>
    Auth,
    /// <summary>
    /// Add user    /// </summary>
    CreateUser
  }

3. Enumeration of operation process

Used to identify the current operation, which stage is in, and different processing is done at different stages.

/// <summary>
  /// Operation process  /// </summary>
  enum OperationStage
  {
    /// <summary>
    /// default    /// </summary>
    Default,
    /// <summary>
    /// Step 1    /// </summary>
    First,
    /// <summary>
    /// Step 2    /// </summary>
    Second,
    /// <summary>
    /// Step 3    /// </summary>
    Third
  }

4. Session cache item

The items that are cached, which record the operation type, operation steps and session objects. In order to facilitate Session management, the last access time is also added to whether the identifier is automatically cleared.

class SessionItem
  {
    /// <summary>
    /// Operation type    /// </summary>
    public Operation Oper { get; set; }
    /// <summary>
    /// Current steps    /// </summary>
    public OperationStage Stage { get; set; }
    /// <summary>
    /// Data object    /// </summary>
    public object Data { get; set; }
    /// <summary>
    /// Whether to delete automatically    /// </summary>
    public bool AutoRemove
    {
      get;
      set;
    }
    /// <summary>
    /// Last updated time    /// </summary>
    public DateTime UpdateTime { get; set; }
  }

2. Add Session 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 an object to provide business processing data.

class AuthSessionItem
  {
    /// <summary>
    /// username    /// </summary>
    public string FromUserName { get; set; }
    /// <summary>
    /// account    /// </summary>
    public string Code { get; set; }
    /// <summary>
    /// Unique ID    /// </summary>
    public string ID { get; set; }
  }

2. Authentication processing process

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

2) Prompt to enter personal account information

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

4) WeChat users enter card number information, the server records card number information, and call specific authentication logic

5) The user authentication is passed, bind WeChat OpenId, prompts that the information is successfully bound, and the session is cleared.

During the authentication process, it is necessary to verify the legality of the user's input information, and during the session, the user is supported to exit the current operation.

/// <summary>
    ///Certified user information    /// </summary>
    /// <param name="tm"></param>
    /// <returns></returns>
    private bool Auth(TextMessage tm, ref string response)
    {
      SessionItem sessionItem = null;
      if ((, "Auth", ))
      {
        //Check whether it has been certified, business component verification        if (())
        {
          //If it has been certified, please prompt           = "You have already certified, no need to re-certify!";          
        }
        else
        {
          AuthSessionItem authSessionItem = new AuthSessionItem();
           = ;

           = ;
           = ;
           = authSessionItem;
          (, sessionItem);

          //Enter the account number, and write the data and steps to the cache           = "Please enter your personal account";
        }

        response = ResponseText(tm);
        return false;
      }

      //Get user information from Session      sessionItem = () as SessionItem;
      //If the session exists and the current operation is user authentication      if (sessionItem != null &&  == )
      {
        if ( == )
        {
           = ();
          if (() ||  > 20)
          {
             = "The personal account you entered is illegal, please re-enter.";
            response = ResponseText(tm);
            return false;
          }
          AuthSessionItem authSessionItem =  as AuthSessionItem;
          if (authSessionItem != null)
          {
             = ;
          }

          //Update cache           = ;
          (, sessionItem);
           = "Please enter your employee card number!\nPlease enter Exit to exit the certification.";
          response = ResponseText(tm); 
        }
        else if ( == )
        {
          string cardNum = null;
          if (!(, out cardNum))
          {            
             = "The employee card number is illegal, please re-enter.\nPlease enter Exit to exit the certification.";
            response = ResponseText(tm);
            return false;
          }
          AuthSessionItem authSessionItem =  as AuthSessionItem;
          if (authSessionItem != null)
          {
             = cardNum;
          }
          //Certification          string message;
          if ((authSessionItem, out message))
          {
             = "Congratulations, you have successfully certified and can use the contact book query function.";
            //Clean the cache            ();
            response = ResponseText(tm);
            return true;
          }
          else if (!(message))
          {
             = message;
          }
          else
          {
             = "The information you entered is incorrect.\nPlease enter: Auth!";
          }
          //The process ends: Clean up Session          ();
          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. When exiting the current operation, the session information needs to be cleaned.

/// <summary>
    /// Exit and clean the Session    /// </summary>
    /// <param name="tm"></param>
    /// <param name="response"></param>
    /// <returns></returns>
    private bool Exit(TextMessage tm, ref string response)
    {
      //quit      if ((, "Exit", ))
      {
        //Clear Session        ();
         = "You have exited the current operation, please perform other operations.";
        response = ResponseText(tm);
        return true;
      }

      return false;
    }

3. User authentication is passed and bound to WeChat account

The user authentication is passed and bound to WeChat OpenId. Through OpenId, you can query address book, personal points, and consumption records. User authentication is an identity authentication process and a user binding process. After passing the user's identity authentication, you can check the 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 achieve more and more complex business applications through small text input boxes. Of course, it is still more intuitive and convenient to enter information by providing web pages.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.