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


  1. [csharp] view plain copy
     
    1. using AIOWeb.Models;  
    2. using Newtonsoft.Json;  
    3. using Newtonsoft.Json.Linq;  
    4. using System;  
    5. using System.Collections.Generic;  
    6. using System.Data;  
    7. using System.Data.SqlClient;  
    8. using System.Linq;  
    9. using System.Web;  
    10.   
    11. namespace AIOWeb  
    12. {  
    13.     /// <summary>  
    14.     /// wxapi 的摘要说明  
    15.     /// </summary>  
    16.     public class wxapi : IHttpHandler  
    17.     {  
    18.         public void ProcessRequest(HttpContext context)  
    19.         {  
    20.             context.Response.ContentType = "text/plain";  
    21.   
    22.             string code = "";  
    23.             string iv = "";  
    24.             string encryptedData = "";  
    25.             try  
    26.             {  
    27.                 code = HttpContext.Current.Request.QueryString["code"].ToString();  
    28.                 iv = HttpContext.Current.Request.QueryString["iv"].ToString();  
    29.                 encryptedData = HttpContext.Current.Request.QueryString["encryptedData"].ToString();  
    30.             }  
    31.             catch (Exception ex)  
    32.             {  
    33.                 context.Response.Write(ex.ToString());  
    34.             }  
    35.   
    36.             string Appid = "wxdb2641f85b04f1b3";  
    37.             string Secret = "8591d8cd7197b9197e17b3275329a1e7";  
    38.             string grant_type = "authorization_code";  
    39.   
    40.             //向微信服务端 使用登录凭证 code 获取 session_key 和 openid   
    41.             string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + Secret + "&js_code=" + code + "&grant_type=" + grant_type;  
    42.             string type = "utf-8";  
    43.   
    44.             AIOWeb.Models.GetUsersHelper GetUsersHelper = new AIOWeb.Models.GetUsersHelper();  
    45.             string j = GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串  
    46.   
    47.             //将字符串转换为json格式  
    48.             JObject jo = (JObject)JsonConvert.DeserializeObject(j);  
    49.   
    50.             result res = new result();  
    51.             try  
    52.             {  
    53.                 //微信服务器验证成功  
    54.                 res.openid = jo["openid"].ToString();  
    55.                 res.session_key = jo["session_key"].ToString();  
    56.             }  
    57.             catch (Exception)  
    58.             {  
    59.                 //微信服务器验证失败  
    60.                 res.errcode = jo["errcode"].ToString();  
    61.                 res.errmsg = jo["errmsg"].ToString();  
    62.             }  
    63.             if (!string.IsNullOrEmpty(res.openid))  
    64.             {  
    65.                 //用户数据解密  
    66.                 GetUsersHelper.AesIV = iv;  
    67.                 GetUsersHelper.AesKey = res.session_key;  
    68.   
    69.                 string result = GetUsersHelper.AESDecrypt(encryptedData);  
    70.   
    71.   
    72.                 //存储用户数据  
    73.                 JObject _usrInfo = (JObject)JsonConvert.DeserializeObject(result);  
    74.   
    75.                 userInfo userInfo = new userInfo();  
    76.                 userInfo.openId = _usrInfo["openId"].ToString();  
    77.   
    78.                 try //部分验证返回值中没有unionId  
    79.                 {  
    80.                     userInfo.unionId = _usrInfo["unionId"].ToString();  
    81.                 }  
    82.                 catch (Exception)  
    83.                 {  
    84.                     userInfo.unionId = "unionId";  
    85.                 }  
    86.                   
    87.                 userInfo.nickName = _usrInfo["nickName"].ToString();  
    88.                 userInfo.gender = _usrInfo["gender"].ToString();  
    89.                 userInfo.city = _usrInfo["city"].ToString();  
    90.                 userInfo.province = _usrInfo["province"].ToString();  
    91.                 userInfo.country = _usrInfo["country"].ToString();  
    92.                 userInfo.avatarUrl = _usrInfo["avatarUrl"].ToString();  
    93.   
    94.                 object watermark = _usrInfo["watermark"].ToString();  
    95.                 object appid = _usrInfo["watermark"]["appid"].ToString();  
    96.                 object timestamp = _usrInfo["watermark"]["timestamp"].ToString();  
    97.  
    98.  
    99.                 #region  
    100.   
    101.   
    102.                 //创建连接池对象(与数据库服务器进行连接)  
    103.                 SqlConnection conn = new SqlConnection("server=127.0.0.1;database=Test;uid=sa;pwd=1");  
    104.                 //打开连接池  
    105.                 conn.Open();  
    106.                 //创建命令对象  
    107.                 string Qrystr = "SELECT * FROM WeChatUsers WHERE openId='" + userInfo.openId + "'";  
    108.                 SqlCommand cmdQry = new SqlCommand(Qrystr, conn);  
    109.                 object  obj = cmdQry.ExecuteScalar();  
    110.                 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))  
    111.                 {  
    112.                     string str = "INSERT INTO WeChatUsers ([UnionId] ,[OpenId],[NickName],[Gender],[City],[Province],[Country],[AvatarUrl],[Appid],[Timestamp],[Memo],[counts])VALUES('" + userInfo.unionId + "','" + userInfo.openId + "','" + userInfo.nickName + "','" + userInfo.gender + "','" + userInfo.city + "','" + userInfo.province + "','" + userInfo.country + "','" + userInfo.avatarUrl + "','" + appid.ToString() + "','" + timestamp.ToString() + "','来自微信小程序','1')";  
    113.   
    114.                     SqlCommand cmdUp = new SqlCommand(str, conn);  
    115.                     // 执行操作  
    116.                     try  
    117.                     {  
    118.                         int row = cmdUp.ExecuteNonQuery();  
    119.                     }  
    120.                     catch (Exception ex)  
    121.                     {  
    122.                         context.Response.Write(ex.ToString());  
    123.                     }  
    124.                 }  
    125.                 else  
    126.                 {  
    127.                     //多次访问,记录访问次数counts   更新unionId是预防最初没有,后期关联后却仍未记录  
    128.                     string str = "UPDATE dbo.WeChatUsers SET counts = counts+1,UnionId = '" + userInfo.unionId + "' WHERE OpenId='" + userInfo.openId + "'";  
    129.                     SqlCommand cmdUp = new SqlCommand(str, conn);  
    130.                     int row = cmdUp.ExecuteNonQuery();  
    131.                 }  
    132.                  
    133.                 //关闭连接池  
    134.                 conn.Close();  
    135.                 #endregion  
    136.   
    137.                 //返回解密后的用户数据  
    138.                 context.Response.Write(result);  
    139.             }  
    140.             else  
    141.             {  
    142.                 context.Response.Write(j);  
    143.             }  
    144.         }  
    145.   
    146.         public bool IsReusable  
    147.         {  
    148.             get  
    149.             {  
    150.                 return false;  
    151.             }  
    152.         }  
    153.     }  
    154. }  


     

     

     

    GetUsersHelper 帮助类

     

    [csharp] view plain copy
     
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.IO;  
    4. using System.Linq;  
    5. using System.Security.Cryptography;  
    6. using System.Text;  
    7. using System.Threading.Tasks;  
    8.   
    9. namespace AIOWeb.Models  
    10. {  
    11.     public class GetUsersHelper  
    12.     {  
    13.   
    14.         /// <summary>  
    15.         /// 获取链接返回数据  
    16.         /// </summary>  
    17.         /// <param name="Url">链接</param>  
    18.         /// <param name="type">请求类型</param>  
    19.         /// <returns></returns>  
    20.         public  string GetUrltoHtml(string Url, string type)  
    21.         {  
    22.             try  
    23.             {  
    24.                 System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);  
    25.                 // Get the response instance.  
    26.                 System.Net.WebResponse wResp = wReq.GetResponse();  
    27.                 System.IO.Stream respStream = wResp.GetResponseStream();  
    28.                 // Dim reader As StreamReader = New StreamReader(respStream)  
    29.                 using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))  
    30.                 {  
    31.                     return reader.ReadToEnd();  
    32.                 }  
    33.             }  
    34.             catch (System.Exception ex)  
    35.             {  
    36.                 return ex.Message;  
    37.             }  
    38.         }  
    39.         #region 微信小程序用户数据解密  
    40.   
    41.         public static string AesKey;  
    42.         public static string AesIV;  
    43.   
    44.         /// <summary>  
    45.         /// AES解密  
    46.         /// </summary>  
    47.         /// <param name="inputdata">输入的数据encryptedData</param>  
    48.         /// <param name="AesKey">key</param>  
    49.         /// <param name="AesIV">向量128</param>  
    50.         /// <returns name="result">解密后的字符串</returns>  
    51.         public string AESDecrypt(string inputdata)  
    52.         {  
    53.             try  
    54.             {  
    55.                 AesIV = AesIV.Replace(" ", "+");  
    56.                 AesKey = AesKey.Replace(" ", "+");  
    57.                 inputdata = inputdata.Replace(" ", "+");  
    58.                 byte[] encryptedData = Convert.FromBase64String(inputdata);  
    59.   
    60.                 RijndaelManaged rijndaelCipher = new RijndaelManaged();  
    61.                 rijndaelCipher.Key = Convert.FromBase64String(AesKey); // Encoding.UTF8.GetBytes(AesKey);  
    62.                 rijndaelCipher.IV = Convert.FromBase64String(AesIV);// Encoding.UTF8.GetBytes(AesIV);  
    63.                 rijndaelCipher.Mode = CipherMode.CBC;  
    64.                 rijndaelCipher.Padding = PaddingMode.PKCS7;  
    65.                 ICryptoTransform transform = rijndaelCipher.CreateDecryptor();  
    66.                 byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);  
    67.                 string result = Encoding.UTF8.GetString(plainText);  
    68.   
    69.                 return result;  
    70.             }  
    71.             catch (Exception)  
    72.             {  
    73.                 return null;  
    74.   
    75.             }  
    76.         }  
    77.         #endregion  
    78.     }  
    79. }  


posted @ 2017-05-15 21:53  网络蚂蚁  阅读(4073)  评论(0编辑  收藏  举报