search
HomeWeChat AppletMini Program DevelopmentHow the WeChat applet server obtains user decrypted information

This article mainly introduces relevant information about the example code of C# WeChat applet server to obtain user decrypted information. Friends in need can refer to

C# WeChat applet server to obtain user decrypted information Example code

Implementation code:

using AIOWeb.Models; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 
using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Web; 
 
namespace AIOWeb 
{ 
  /// <summary> 
  /// wxapi 的摘要说明 
  /// </summary> 
  public class wxapi : IHttpHandler 
  { 
    public void ProcessRequest(HttpContext context) 
    { 
      context.Response.ContentType = "text/plain"; 
 
      string code = ""; 
      string iv = ""; 
      string encryptedData = ""; 
      try 
      { 
        code = HttpContext.Current.Request.QueryString["code"].ToString(); 
        iv = HttpContext.Current.Request.QueryString["iv"].ToString(); 
        encryptedData = HttpContext.Current.Request.QueryString["encryptedData"].ToString(); 
      } 
      catch (Exception ex) 
      { 
        context.Response.Write(ex.ToString()); 
      } 
 
      string Appid = "wxdb2641f85b04f1b3"; 
      string Secret = "8591d8cd7197b9197e17b3275329a1e7"; 
      string grant_type = "authorization_code"; 
 
      //向微信服务端 使用登录凭证 code 获取 session_key 和 openid  
      string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + Secret + "&js_code=" + code + "&grant_type=" + grant_type; 
      string type = "utf-8"; 
 
      AIOWeb.Models.GetUsersHelper GetUsersHelper = new AIOWeb.Models.GetUsersHelper(); 
      string j = GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串 
 
      //将字符串转换为json格式 
      JObject jo = (JObject)JsonConvert.DeserializeObject(j); 
 
      result res = new result(); 
      try 
      { 
        //微信服务器验证成功 
        res.openid = jo["openid"].ToString(); 
        res.session_key = jo["session_key"].ToString(); 
      } 
      catch (Exception) 
      { 
        //微信服务器验证失败 
        res.errcode = jo["errcode"].ToString(); 
        res.errmsg = jo["errmsg"].ToString(); 
      } 
      if (!string.IsNullOrEmpty(res.openid)) 
      { 
        //用户数据解密 
        GetUsersHelper.AesIV = iv; 
        GetUsersHelper.AesKey = res.session_key; 
 
        string result = GetUsersHelper.AESDecrypt(encryptedData); 
 
 
        //存储用户数据 
        JObject _usrInfo = (JObject)JsonConvert.DeserializeObject(result); 
 
        userInfo userInfo = new userInfo(); 
        userInfo.openId = _usrInfo["openId"].ToString(); 
 
        try //部分验证返回值中没有unionId 
        { 
          userInfo.unionId = _usrInfo["unionId"].ToString(); 
        } 
        catch (Exception) 
        { 
          userInfo.unionId = "unionId"; 
        } 
         
        userInfo.nickName = _usrInfo["nickName"].ToString(); 
        userInfo.gender = _usrInfo["gender"].ToString(); 
        userInfo.city = _usrInfo["city"].ToString(); 
        userInfo.province = _usrInfo["province"].ToString(); 
        userInfo.country = _usrInfo["country"].ToString(); 
        userInfo.avatarUrl = _usrInfo["avatarUrl"].ToString(); 
 
        object watermark = _usrInfo["watermark"].ToString(); 
        object appid = _usrInfo["watermark"]["appid"].ToString(); 
        object timestamp = _usrInfo["watermark"]["timestamp"].ToString(); 
 
 
        #region 
 
 
        //创建连接池对象(与数据库服务器进行连接) 
        SqlConnection conn = new SqlConnection("server=127.0.0.1;database=Test;uid=sa;pwd=1"); 
        //打开连接池 
        conn.Open(); 
        //创建命令对象 
        string Qrystr = "SELECT * FROM WeChatUsers WHERE openId=&#39;" + userInfo.openId + "&#39;"; 
        SqlCommand cmdQry = new SqlCommand(Qrystr, conn); 
        object obj = cmdQry.ExecuteScalar(); 
        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 
        { 
          string str = "INSERT INTO WeChatUsers ([UnionId] ,[OpenId],[NickName],[Gender],[City],[Province],[Country],[AvatarUrl],[Appid],[Timestamp],[Memo],[counts])VALUES(&#39;" + userInfo.unionId + "&#39;,&#39;" + userInfo.openId + "&#39;,&#39;" + userInfo.nickName + "&#39;,&#39;" + userInfo.gender + "&#39;,&#39;" + userInfo.city + "&#39;,&#39;" + userInfo.province + "&#39;,&#39;" + userInfo.country + "&#39;,&#39;" + userInfo.avatarUrl + "&#39;,&#39;" + appid.ToString() + "&#39;,&#39;" + timestamp.ToString() + "&#39;,&#39;来自微信小程序&#39;,&#39;1&#39;)"; 
 
          SqlCommand cmdUp = new SqlCommand(str, conn); 
          // 执行操作 
          try 
          { 
            int row = cmdUp.ExecuteNonQuery(); 
          } 
          catch (Exception ex) 
          { 
            context.Response.Write(ex.ToString()); 
          } 
        } 
        else 
        { 
          //多次访问,记录访问次数counts  更新unionId是预防最初没有,后期关联后却仍未记录 
          string str = "UPDATE dbo.WeChatUsers SET counts = counts+1,UnionId = &#39;" + userInfo.unionId + "&#39; WHERE OpenId=&#39;" + userInfo.openId + "&#39;"; 
          SqlCommand cmdUp = new SqlCommand(str, conn); 
          int row = cmdUp.ExecuteNonQuery(); 
        } 
         
        //关闭连接池 
        conn.Close(); 
        #endregion 
 
        //返回解密后的用户数据 
        context.Response.Write(result); 
      } 
      else 
      { 
        context.Response.Write(j); 
      } 
    } 
 
    public bool IsReusable 
    { 
      get 
      { 
        return false; 
      } 
    } 
  } 
}

GetUsersHelper helper class

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Security.Cryptography; 
using System.Text; 
using System.Threading.Tasks; 
 
namespace AIOWeb.Models 
{ 
  public class GetUsersHelper 
  { 
 
    /// <summary> 
    /// 获取链接返回数据 
    /// </summary> 
    /// <param name="Url">链接</param> 
    /// <param name="type">请求类型</param> 
    /// <returns></returns> 
    public string GetUrltoHtml(string Url, string type) 
    { 
      try 
      { 
        System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); 
        // Get the response instance. 
        System.Net.WebResponse wResp = wReq.GetResponse(); 
        System.IO.Stream respStream = wResp.GetResponseStream(); 
        // Dim reader As StreamReader = New StreamReader(respStream) 
        using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) 
        { 
          return reader.ReadToEnd(); 
        } 
      } 
      catch (System.Exception ex) 
      { 
        return ex.Message; 
      } 
    } 
    #region 微信小程序用户数据解密 
 
    public static string AesKey; 
    public static string AesIV; 
 
    /// <summary> 
    /// AES解密 
    /// </summary> 
    /// <param name="inputdata">输入的数据encryptedData</param> 
    /// <param name="AesKey">key</param> 
    /// <param name="AesIV">向量128</param> 
    /// <returns name="result">解密后的字符串</returns> 
    public string AESDecrypt(string inputdata) 
    { 
      try 
      { 
        AesIV = AesIV.Replace(" ", "+"); 
        AesKey = AesKey.Replace(" ", "+"); 
        inputdata = inputdata.Replace(" ", "+"); 
        byte[] encryptedData = Convert.FromBase64String(inputdata); 
 
        RijndaelManaged rijndaelCipher = new RijndaelManaged(); 
        rijndaelCipher.Key = Convert.FromBase64String(AesKey); // Encoding.UTF8.GetBytes(AesKey); 
        rijndaelCipher.IV = Convert.FromBase64String(AesIV);// Encoding.UTF8.GetBytes(AesIV); 
        rijndaelCipher.Mode = CipherMode.CBC; 
        rijndaelCipher.Padding = PaddingMode.PKCS7; 
        ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); 
        byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); 
        string result = Encoding.UTF8.GetString(plainText); 
 
        return result; 
      } 
      catch (Exception) 
      { 
        return null; 
 
      } 
    } 
    #endregion 
  } 
}

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to solve the problem that the WeChat mini program cannot request data when requesting the server mobile phone preview

About WeChat Implementation of pop-up boxes and modal boxes in mini programs

The above is the detailed content of How the WeChat applet server obtains user decrypted information. For more information, please follow other related articles on 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

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment