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='" + 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],1489339825,[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 } }
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!