搜索
首页微信小程序小程序开发微信小程序服务端获取用户解密信息的方法

这篇文章主要介绍了 C#微信小程序服务端获取用户解密信息实例代码的相关资料,需要的朋友可以参考下

 C#微信小程序服务端获取用户解密信息实例代码

实现代码:

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 帮助类

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 
  } 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

如何解决微信小程序请求服务器手机预览请求不到数据的问题

关于微信小程序中弹框和模态框的实现

以上是微信小程序服务端获取用户解密信息的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用