C# · 12月 19, 2021

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

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

实现代码:

namespace AIOWeb
{
///
/// wxapi 的摘要说明
///
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”; //向微信服务端 使用<a href=”https://www.jb51.cc/tag/denglu/” target=”_blank” class=”keywords”>登录</a>凭证 code <a href=”https://www.jb51.cc/tag/huoqu/” target=”_blank” class=”keywords”>获取</a> 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);//<a href=”https://www.jb51.cc/tag/huoqu/” target=”_blank” class=”keywords”>获取</a>微信服务器返回字符串 //将<a href=”https://www.jb51.cc/tag/zifuchuanzhuanhuan/” target=”_blank” class=”keywords”>字符串转换</a>为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)) { //<a href=”https://www.jb51.cc/tag/yonghu/” target=”_blank” class=”keywords”>用户</a>数据解密 GetUsersHelper.AesIV = iv; GetUsersHelper.AesKey = res.session_key; string result = GetUsersHelper.AESDecrypt(encryptedData); //存储<a href=”https://www.jb51.cc/tag/yonghu/” target=”_blank” class=”keywords”>用户</a>数据 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 //创建连接池对象(与<a href=”https://www.jb51.cc/tag/shujuku/” target=”_blank” class=”keywords”>数据库</a>服务器进行连接) <a href=”https://www.jb51.cc/tag/sql/” target=”_blank” class=”keywords”>sql</a>Connection conn = new <a href=”https://www.jb51.cc/tag/sql/” target=”_blank” class=”keywords”>sql</a>Connection(“server=127.0.0.1;database=Test;uid=sa;pwd=1″); //打开连接池 conn.<a href=”https://www.jb51.cc/tag/open/” target=”_blank” class=”keywords”>open()</a>; //创建命令对象 string Qrystr = “SELECT * FROM WeChatUsers WHERE openId='” + userInfo.openId + “‘”; <a href=”https://www.jb51.cc/tag/sql/” target=”_blank” class=”keywords”>sql</a>Command cmdQry = new <a href=”https://www.jb51.cc/tag/sql/” target=”_blank” class=”keywords”>sql</a>Command(Qrystr,conn); object obj = cmdQry.ExecuteScalar(); if ((Object.Equals(obj,null)) || (Object.Equals(obj,Sy<a href=”https://www.jb51.cc/tag/stem/” target=”_blank” class=”keywords”>stem</a>.DBNull.Value))) { string str = “INSERT INTO WeChatUsers ([UnionId],[OpenId],[NickName],[Gender],[City],[Province],[Country],[AvatarUrl],[Appid],1639905844,[Memo],[counts])VALUES(‘” + userInfo.unionId + “‘,'” + userInfo.openId + “‘,'” + userInfo.nickName + “‘,'” + userInfo.gender + “‘,'” + userInfo.city + “‘,'” + userInfo.province + “‘,'” + userInfo.country + “‘,'” + userInfo.avatarUrl + “‘,'” + appid.ToString() + “‘,'” + timestamp.ToString() + “‘,’来自<a href=”https://www.jb51.cc/tag/weixinxiaochengxu/” target=”_blank” class=”keywords”>微信小程序</a>’,’1′)”; <a href=”https://www.jb51.cc/tag/sql/” target=”_blank” class=”keywords”>sql</a>Command cmdUp = new <a href=”https://www.jb51.cc/tag/sql/” target=”_blank” class=”keywords”>sql</a>Command(str,conn); // 执行操作 try { int row = cmdUp.ExecuteNonQuery(); } catch (Exception ex) { context.Response.Write(ex.ToString()); } } else { //多次访问,记录访问<a href=”https://www.jb51.cc/tag/cishu/” target=”_blank” class=”keywords”>次数</a>counts 更新unionId是预防最初没有,后期关联后却仍未记录 string str = “UPDATE dbo.WeChatUsers SET counts = counts+1,UnionId = ‘” + userInfo.unionId + “‘ WHERE OpenId='” + userInfo.openId + “‘”; <a href=”https://www.jb51.cc/tag/sql/” target=”_blank” class=”keywords”>sql</a>Command cmdUp = new <a href=”https://www.jb51.cc/tag/sql/” target=”_blank” class=”keywords”>sql</a>Command(str,conn); int row = cmdUp.ExecuteNonQuery(); } //<a href=”https://www.jb51.cc/tag/guanbi/” target=”_blank” class=”keywords”>关闭</a>连接池 conn.Close(); #endregion //返回解密后的<a href=”https://www.jb51.cc/tag/yonghu/” target=”_blank” class=”keywords”>用户</a>数据 context.Response.Write(result); } else { context.Response.Write(j); } } public bool IsReusable { get { return false; } }

}
}

GetUsersHelper 帮助类

namespace AIOWeb.Models
{
public class GetUsersHelper
{

/// <summary> /// <a href=”https://www.jb51.cc/tag/huoqu/” target=”_blank” class=”keywords”>获取</a><a href=”https://www.jb51.cc/tag/lianjie/” target=”_blank” class=”keywords”>链接</a>返回数据 /// </summary> /// <param name=”Url”&gt;<a href=”https://www.jb51.cc/tag/lianjie/” target=”_blank” class=”keywords”>链接</a></param> /// <param name=”type”&gt;请求类型</param> /// <returns></returns> public string GetUrltoHtml(string Url,string type) { try { Sy<a href=”https://www.jb51.cc/tag/stem/” target=”_blank” class=”keywords”>stem</a>.Net.WebRequest wReq = Sy<a href=”https://www.jb51.cc/tag/stem/” target=”_blank” class=”keywords”>stem</a>.Net.WebRequest.Create(Url); // Get the response instance. Sy<a href=”https://www.jb51.cc/tag/stem/” target=”_blank” class=”keywords”>stem</a>.Net.WebResponse wResp = wReq.GetResponse(); Sy<a href=”https://www.jb51.cc/tag/stem/” target=”_blank” class=”keywords”>stem</a>.IO.Stream respStream = wResp.GetResponseStream(); // Dim reader As StreamReader = New StreamReader(respStream) using (Sy<a href=”https://www.jb51.cc/tag/stem/” target=”_blank” class=”keywords”>stem</a>.IO.StreamReader reader = new Sy<a href=”https://www.jb51.cc/tag/stem/” target=”_blank” class=”keywords”>stem</a>.IO.StreamReader(respStream,Encoding.GetEncoding(type))) { return reader.ReadToEnd(); } } catch (Sy<a href=”https://www.jb51.cc/tag/stem/” target=”_blank” class=”keywords”>stem</a>.Exception ex) { return ex.Message; } } #region <a href=”https://www.jb51.cc/tag/weixinxiaochengxu/” target=”_blank” class=”keywords”>微信小程序</a><a href=”https://www.jb51.cc/tag/yonghu/” target=”_blank” class=”keywords”>用户</a>数据解密 public static string AesKey; public static string AesIV; /// <summary> /// AES解密 /// </summary> /// <param name=”inputdata”&gt;输入的数据encryptedData</param> /// <param name=”AesKey”&gt;key</param> /// <param name=”AesIV”&gt;向量128</param> /// <returns name=”result”&gt;解密后的字符串</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,encryptedData.Length); string result = Encoding.UTF8.GetString(plainText); return result; } catch (Exception) { return null; } } #endregion

}
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!