DDR爱好者之家 Design By 杰米
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 + "&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='" + userInfo.openId + "'"; 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],1617630051,[Memo],[counts])VALUES('" + userInfo.unionId + "','" + userInfo.openId + "','" + userInfo.nickName + "','" + userInfo.gender + "','" + userInfo.city + "','" + userInfo.province + "','" + userInfo.country + "','" + userInfo.avatarUrl + "','" + appid.ToString() + "','" + timestamp.ToString() + "','来自微信小程序','1')"; 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 = '" + userInfo.unionId + "' WHERE OpenId='" + userInfo.openId + "'"; 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 } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米
暂无评论...
更新日志
2024年11月27日
2024年11月27日
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]