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

    GetUsersHelper 帮助类

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