最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C#微信小程序服务端获取用户解密信息实例代码
时间:2022-06-25 07:50:18 编辑:袖梨 来源:一聚教程网
C#微信小程序服务端获取用户解密信息实例代码
实现代码:
代码如下 | 复制代码 |
usingAIOWeb.Models; usingNewtonsoft.Json; usingNewtonsoft.Json.Linq; usingSystem; usingSystem.Collections.Generic; usingSystem.Data; usingSystem.Data.SqlClient; usingSystem.Linq; usingSystem.Web;
namespaceAIOWeb { /// /// wxapi 的摘要说明 /// publicclasswxapi : IHttpHandler { publicvoidProcessRequest(HttpContext context) { context.Response.ContentType ="text/plain";
stringcode =""; stringiv =""; stringencryptedData =""; 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()); }
stringAppid ="wxdb2641f85b04f1b3"; stringSecret ="8591d8cd7197b9197e17b3275329a1e7"; stringgrant_type ="authorization_code";
//向微信服务端 使用登录凭证 code 获取 session_key 和 openid stringurl ="https://api.weixin.qq.com/sns/jscode2session?appid="+ Appid +"&secret="+ Secret +"&js_code="+ code +"&grant_type="+ grant_type; stringtype ="utf-8";
AIOWeb.Models.GetUsersHelper GetUsersHelper =newAIOWeb.Models.GetUsersHelper(); stringj = GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串
//将字符串转换为json格式 JObject jo = (JObject)JsonConvert.DeserializeObject(j);
result res =newresult(); 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;
stringresult = GetUsersHelper.AESDecrypt(encryptedData);
//存储用户数据 JObject _usrInfo = (JObject)JsonConvert.DeserializeObject(result);
userInfo userInfo =newuserInfo(); 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();
objectwatermark = _usrInfo["watermark"].ToString(); objectappid = _usrInfo["watermark"]["appid"].ToString(); objecttimestamp = _usrInfo["watermark"]["timestamp"].ToString();
#region
//创建连接池对象(与数据库服务器进行连接) SqlConnection conn =newSqlConnection("server=127.0.0.1;database=Test;uid=sa;pwd=1"); //打开连接池 conn.Open(); //创建命令对象 stringQrystr ="SELECT * FROM WeChatUsers WHERE openId='"+ userInfo.openId +"'"; SqlCommand cmdQry =newSqlCommand(Qrystr, conn); objectobj = cmdQry.ExecuteScalar(); if((Object.Equals(obj,null)) || (Object.Equals(obj, System.DBNull.Value))) { stringstr ="INSERT INTO WeChatUsers ([UnionId] ,[OpenId],[NickName],[Gender],[City],[Province],[Country],[AvatarUrl],[Appid],1664178218,[Memo],[counts])VALUES('"+ userInfo.unionId +"','"+ userInfo.openId +"','"+ userInfo.nickName +"','"+ userInfo.gender +"','"+ userInfo.city +"','"+ userInfo.province +"','"+ userInfo.country +"','"+ userInfo.avatarUrl +"','"+ appid.ToString() +"','"+ timestamp.ToString() +"','来自微信小程序',Ƈ')";
SqlCommand cmdUp =newSqlCommand(str, conn); // 执行操作 try { introw = cmdUp.ExecuteNonQuery(); } catch(Exception ex) { context.Response.Write(ex.ToString()); } } else { //多次访问,记录访问次数counts 更新unionId是预防最初没有,后期关联后却仍未记录 stringstr ="UPDATE dbo.WeChatUsers SET counts = counts+1,UnionId = '"+ userInfo.unionId +"' WHERE OpenId='"+ userInfo.openId +"'"; SqlCommand cmdUp =newSqlCommand(str, conn); introw = cmdUp.ExecuteNonQuery(); }
//关闭连接池 conn.Close(); #endregion
//返回解密后的用户数据 context.Response.Write(result); } else { context.Response.Write(j); } }
publicboolIsReusable { get { returnfalse; } } } } |
GetUsersHelper 帮助类
代码如下 | 复制代码 |
usingSystem; usingSystem.Collections.Generic; usingSystem.IO; usingSystem.Linq; usingSystem.Security.Cryptography; usingSystem.Text; usingSystem.Threading.Tasks;
namespaceAIOWeb.Models { publicclassGetUsersHelper {
/// /// 获取链接返回数据 /// ///链接 ///请求类型 /// publicstringGetUrltoHtml(stringUrl,stringtype) { 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 =newSystem.IO.StreamReader(respStream, Encoding.GetEncoding(type))) { returnreader.ReadToEnd(); } } catch(System.Exception ex) { returnex.Message; } } #region 微信小程序用户数据解密
publicstaticstringAesKey; publicstaticstringAesIV;
/// /// AES解密 /// ///输入的数据encryptedData ///key ///向量128 /// publicstringAESDecrypt(stringinputdata) { try { AesIV = AesIV.Replace(" ","+"); AesKey = AesKey.Replace(" ","+"); inputdata = inputdata.Replace(" ","+"); byte[] encryptedData = Convert.FromBase64String(inputdata);
RijndaelManaged rijndaelCipher =newRijndaelManaged(); 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); stringresult = Encoding.UTF8.GetString(plainText);
returnresult; } catch(Exception) { returnnull;
} } #endregion } } |
相关文章
- 王者荣耀侦探能力大测试攻略 王者荣耀侦探能力大测试怎么过 11-22
- 无期迷途主线前瞻兑换码是什么 11-22
- 原神欧洛伦怎么培养 11-22
- 炉石传说网易云音乐联动怎么玩 11-22
- 永劫无间手游确幸转盘怎么样 11-22
- 无期迷途主线前瞻兑换码是什么 无期迷途主线前瞻直播兑换码介绍 11-22